在iOS OC編程中,很多場景都會使用回調,尤其和C、C++代碼的數據交互上,使用回調,會很方便。那麼在OC中都可以使用那些回調方法呢?總結了以下6種:
int (^block)(int,int);
通過typedef簡化:
typedef int (^block)(int,int);
block bl = ^(int a,int b){
return a+b;
}
//回調函數定義:
- (int)handleBlockCallbackFunc: (block)callback
{
return callback(10,12);
}
回調函數使用:
int ret = [self handleBlockCallbackFunc:
^(int param,__unused int b) {
NSLog(@"Block Msg: %d", param);
return param*2;
}];
警告:
[target performSelector: @selector(callback)];
方式建立回調,則需要對類的回調消息名建立約定,且回調消息名具有獨佔性,即一個類中只能以此消息名進行回調。
[target performSelector: sel];
或是外部傳入字符串建立回調
[target performSelector:NSSelectorFromString(@"callback")];
使用自動引數編譯器特徵(ARC)會產生警告“performSelector may cause a leak because its selector is unknown”
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName: NOTIFY_MSG_UC_COMMON_PLAYER_PLAY // 消息名(字符串)
object:self // 消息源
userInfo:nil]; // 用戶字典(傳遞更多自定義參數)
[nc addObserver: self // 觀察者
selector: @selector(handleNotify_Play:) // 回調
name: NOTIFY_MSG_UC_COMMON_PLAYER_PLAY // 監聽消息
object: nil]; // 消息源
(4).註銷消息
[nc removeObserver: self];
(5).回調定義
- (void) handleNotify_Play:(NSNotification *)note;
只有一個參數
NSNotification*
–name // 消息名
–object // 消息源
–userInfo // 用戶字典
優點:
typedef int (*CBFUNC)(id, SEL, int, int, int); // 定義函數指針類型
int ret = ((CBFUNC)callback)(self, sel, param1, param2, param3); // 強制轉換
這裏的id和SEL只是OBJC系統約定的佔位,自定義回調時無實際意義
IOS回調方法應用場景總結:
(1).單純的回調,且沒有複用的必要,也無IOS版本限制,可採用block
(2).單純的回調,有複用要求,可使用performSelector、objc_msgSend,或是IMP的回調機制
(3).使用自動引數的情況下,儘量不使用performSelector回調傳入的@Selector,防止警告
(4).對象間有較多的互操作,對象有複用的必要,可採用協議
(5).無指定對象的一對多回調採用NSNotificationCenter
(6).有延遲調用等特殊應用的,可以使用performSelector