ios 异步回调选择

异步调用,比较常用,比如网络请求等,都需要等别的模块处理完成后,我们这边再进行处理,然而外部什么时候能处理完是一个未知数,我们不能一直在等待,所以就需要做异步回调了

  1. handler-block(块)

  2. delegate(协议)

  3. notification(通知)

  4. addTarget (事件)

目前我就知道这些方法,其实原理都差不多,都是使用观察者模式,下面一一分析和使用demo:

1.handler-block(块)

block方式是比较常适用于网络请求的回调处理的

特点:就是一次调用一次反馈,一对一的模式,而且必有反馈,无论失败还是成功、易用易读

typedef void (^choiceCompletionBlock)(int index);
- (void)showTipAlert:(NSString *)message completion:(choiceCompletionBlock)completion;

[[KSAlertView shareAlertView] showTipAlert:nameErrorInfo completion:^(int index) {
            [_nameField becomeFirstResponder];
        }];

2.delegate(协议)

delegate是ios库比较喜欢用的,如UITableView、UIAlertView等

特点:是使用模块或者类会产生多种事件或数据,外部可以选择接受、处理或者无视、内传数据、结构性好

@protocol HotWorkConrtentItemDelegate <NSObject>

-(void)didSelectWithIndex:(NSInteger)index section:(NSInteger)section;

@end

if (_delegate && [_delegate respondsToSelector:@selector(didSelectWithIndex:section:)]) {
        [_delegate didSelectWithIndex:_hotWorkIndex section:_section];
    }

3.notification(通知)

notification是有NSNotificationCenter库使用,常用于公用库的反馈

特点:一对多的模式,跨度无限制,一个调用者,能有多个无关的模块接收、灵活

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];

4.addTarget (事件)

addTarget常用于UIControl控件上的事件反馈

特点:持久注册、特殊反馈、多对多、好处理

[_deletePhotoBtn addTarget:self action:@selector(deletePhotoBtnClick:) forControlEvents:UIControlEventTouchUpInside];


转载于:https://my.oschina.net/iq19900204/blog/411818

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值