现在的位置: 首页 > 综合 > 正文

Cocoa设计模式之通知

2012年12月01日 ⁄ 综合 ⁄ 共 916字 ⁄ 字号 评论关闭

  以前觉得通知比较难搞,总是避免。但是折腾一番后发现真的是个好东西,用起来很好。整理下使用方法。

一、首先,在viewDidLoad或者其他地方添加通知

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateTable:) name:@"updateTable" object:nil];
NSNotificationCenter为一个单例模式的类,能调用的方法也比较有限,可以自行查阅api。addobserver:后面的参数为你当前的类,或者你要接收消息的类。selector:收到通知后需要执行的方法。name为通知的名字,object可以作为消息传递的参数。

二、定义通知完成后所要执行的方法
- (void)updateTable:(NSNotification *)sender{
    NSLog(@"通知成功");
    
    NSDictionary *dictionary = (NSDictionary *)[sender userInfo];
    NSArray *array = [[NSArray alloc] initWithArray:[dictionary objectForKey:@"names"]];
    
    NSLog(@"%@,%@",[array objectAtIndex:0],[array objectAtIndex:1]);
}

sender为发布通知的时候传递过来的参数

三、在你需要调用方法时发布通知

 [[NSNotificationCenter defaultCenter] postNotificationName:@"updateTable" object:nil userInfo:dictionary];

dictionary为之前定义的参数

 NSArray *array = [[NSArray alloc] initWithObjects:@"foxbabe",@"philiphu", nil];
    NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:array,@"names", nil];

抱歉!评论已关闭.