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

发送通告,发送通告时可以带一个参数,此参数需为NSDictionary字典类型:

  1. NSMutableDictionary *dic = [[NSMutableDictionary alloc] init]; 
  2. [dic setObject:@"I'm a notification!" forKey:@"content"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"myNotification" object:self userInfo:(NSDictionary *)dic]; 

注册通告观察器:

  1. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getContent:) name:@"
    myNotification" object:nil]; 

接收到通告后调用方法:

  1. - (void)getContent:(NSNotification *)note 
  2.     NSDictionary *dic = [note userInfo]; 
  3.     NSLog("The Content of myNotification : %@", [dic objectForKey:@"content"]); 
  4. }    

10.26更新

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

取消注册:

  1. - (void)dealloc 

  2.     [[NSNotificationCenter defaultCenter] removeObserver:self];
        [super dealloc];