发送通告,发送通告时可以带一个参数,此参数需为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]; }