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];


你可能感兴趣的:(ios,异步)