NSNotificationCenter

新建一个继承于UIViewControll的类,并在.m中添加如下代码

-(void)doSomeThing:(NSNotification *)aNote
{
NSDictionary *dict = [aNote object];
NSLog(@"%@",dict);
}
- (void)loadView
{
[super loadView];
NSString *myString = @"some Value";
NSDictionary *myDict = [[NSDictionary alloc]initWithObjectsAndKeys:myString,@"first", nil];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(doSomeThing:) name:@"notification" object:nil];

[[NSNotificationCenter defaultCenter]postNotificationName:@"notification" object:myDict];

}

设置通知:

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(doSomeThing:) name:@"notification" object:nil];

addObserver 这个是观察者,就是说 在什么地方接收通知;

 selector 这个是收到通知后,调用何种方法;

 name: 这个是通知的名字,也是通知的唯一标示,编译器就通过这个找到通知的。

   object:  对象,当设定为nil时,默认为所有名称为以上消息名称的(notification)都接收不管发送者是谁。

发送通知:

[[NSNotificationCenter defaultCenter]postNotificationName:@"notification" object:myDict];

postNotificationName:通知的名字,也是通知的唯一标示,编译器就通过这个找到通知的。

object:对象,当设定为nil时,默认为所有名称为以上消息名称的(notification)都发送。

小例子仅仅是在一个类下的通知,实际来说通知更多的应用于不同的类之间传递信息。

posted @ 2012-01-31 15:38  SuperHappy  阅读(1635)  评论(0编辑  收藏  举报