NSNotification

来源:互联网 发布:数据备份还原系统 编辑:程序博客网 时间:2024/05/22 06:04

NSNotification

(2012-07-05 14:50:53)
 

不同类关联事件通知,

如:类A发生某事件然后通知类B,类B获取通知,然后采取某行动,

 

发送方:

作成通知:

NSNotification *cn = [NSNotification notificationWithName:@"Today"    
                                                          object:self]; 

通知开始执行:

[[NSNotificationCenter defaultCenter] postNotification: cn];  

 

收信方:

取得通知:

NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 

去通知中心要求得到通知同时呼叫需执行的方法:

 [nc addObserver:self selector:@selector(hello)  
                         name:@"Today" 
                           object:nil];  
-(void)hello{    //处理   } 

 

 

发送方:

作成要传送的值:

NSDictionary *dic = [NSDictionary dictionaryWithObject:@"HOGE"         
                                                      forKey:@"KEY" ]; 

作成通知:

NSNotification *n = [NSNotification notificationWithName:@"Today"  
  object:self  
 userInfo:dic]; 

通知开始执行:

[[NSNotificationCenter defaultCenter] postNotification: cn];  

 

收信方:

取得通知:

NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 

去通知中心要求得到通知同时呼叫需执行的方法:

 [nc addObserver:self selector:@selector(hello:)  
                            name:@"Today" 
                      object:nil];  
-(void)hello:(NSNotificationCenter*)center{  
    //从通知得到的值 center      
NSString *value = [[center userInfo] objectForKey:@"KEY"];  
原创粉丝点击