【IOS开发】通告中心NSNotificationCenter

在IOS开发中,通告的作用不言而喻,它在一个项目中就像是一个特权,不受类等的约束,方便至极,对于每一个通告,区分他们的标示是他们的名字name。



发送通告,发送通告时可以带一个参数,此参数需为NSDictionary字典类型:
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init]; [dic setObject:@"I'm a notification!" forKey:@"content"]; [[NSNotificationCenter defaultCenter] postNotificationName:@"myNotification" object:self userInfo:(NSDictionary *)dic];



注册通告观察器:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getContent:) name:@"myNotification" object:nil]; 







接收到通告后调用方法:
- (void)getContent:(NSNotification *)note {     NSDictionary *dic = [note userInfo];     NSLog("The Content of myNotification : %@", [dic objectForKey:@"content"]); }  




10.26更新

通告中心不会保留观察器,在通告中心注册过的对象必须在释放前取消注册。否则,相应的通告再次出现时,通告中心仍然会像该观察器发送消息,因为相应的对象已经释放,所以会导致程序崩溃。

- (void)dealloc {      [[NSNotificationCenter defaultCenter] removeObserver:self];        [super dealloc];

} 

猜你喜欢

转载自android-zhang.iteye.com/blog/1758326