標籤:
認識下三種IOS常見的回調模式。
代理模式作為IOS中最常見的通訊模式,代理幾乎無處不在。
這裡有一個數組,我們首先通過代理的方式將數組傳遞到其他方法中去。
設定協議及方法
- @protocol CallBackDelegate;
- @interface ViewController : UIViewController
- @property (weak, nonatomic) id<CallBackDelegate> delegate;
- @end
- @protocol CallBackDelegate <NSObject>
- - (void)showArrayWithDelegate:(NSArray *)array;
- @end
@interface ViewController () <CallBackDelegate>
點擊按鈕傳遞數組讓其顯示
- - (IBAction)delegateCallBack
- {
- NSDictionary *dict = @{@"array": @[@"Chelsea", @"MUFC", @"Real Madrid"]};
- NSArray *array = dict[@"array"];
- [self.delegate showArrayWithDelegate:array];
- }
調用,顯示
- - (void)showArrayWithDelegate:(NSArray *)array
- {
- _outputLabel.text = array[2];
- }
最重要也是最容易忽略的,就是一定要設定delegate的指向。
完成後螢幕顯示
使用通知中樞
通知中樞的方式可以不用設定代理,但是需要設定觀察者和移除觀察者。
代碼
- - (IBAction)callBack
- {
- NSDictionary *dict = @{@"array": @[@"Chelsea", @"MUFC", @"Real Madrid"]};
- NSArray *array = dict[@"array"];
- [[NSNotificationCenter defaultCenter] postNotificationName:@"OutputArrayNotification" object:array];
- }
註冊和移出觀察者
- - (void)viewWillAppear:(BOOL)animated
- {
- [super viewWillAppear:animated];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(outputWithNote:) name:@"OutputArrayNotification" object:nil];
- }
- - (void)viewDidDisappear:(BOOL)animated
- {
- [super viewDidDisappear:animated];
- [[NSNotificationCenter defaultCenter] removeObserver:self name:@"OutputArrayNotification" object:nil];
- }
顯示
- - (void)outputWithNote:(NSNotification *)aNotification
- {
- NSArray *receiveArray = [aNotification object];
- _outputLabel.text = receiveArray[0];
- }
Block
什麼是Block:從C的聲明符到Objective-C的Blocks文法
塊代碼以閉包得形式將各種內容進行傳遞,可以是代碼,可以是數組無所不能。塊代碼十分方便將不同地方的代碼集中統一,使其易讀性增強。
來看這裡怎麼進行數組傳遞。
typedef void (^Arr_Block)(NSArray *array);
- - (void)showArrayUsingBlock:(Arr_Block)block
- {
- NSDictionary *dict = @{@"array": @[@"Chelsea", @"MUFC", @"Real Madrid"]};
- NSArray *array = dict[@"array"];
- block(array);
- }
調用方法,顯示
- - (IBAction)blockCallBack
- {
- [self showArrayUsingBlock:^(NSArray *array) {
- _outputLabel.text = array[1];
- }];
- }
>
IOS常見的三種回調方法介紹