今天發(fā)現(xiàn)在項目中拋出NSNotificationCenter的事件,一直執(zhí)行不到回調(diào)函數(shù)兔乞。經(jīng)過一番排查辆憔,發(fā)現(xiàn)原來是在注冊時添加了Object參數(shù),發(fā)送時报嵌,卻沒有填充Object參數(shù)虱咧。被坑了良久,在次記錄一下锚国。
代碼簡略如下:
@implementation TWGroupChatViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test:) name:"NOTIFICATION_TEST" object:self];
}
-(void)test:(NSNotification*)notification
{
}
@end
在其他地方調(diào)用的代碼:
[[NSNotificationCenter defaultCenter] postNotificationName:"NOTIFICATION_TEST" object:nil userInfo:nil];
問題所在:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test:) name:"NOTIFICATION_TEST" object:self];這里的object參數(shù)傳入了self腕巡,但是發(fā)出通知的地方,object參數(shù)卻傳入了nil血筑,兩者不一致绘沉,導致注冊的函數(shù)不被調(diào)用煎楣。
改正方法:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test:) name:"NOTIFICATION_TEST" object:nil];
添加事件時,將object參數(shù)傳入nil即可车伞。