NSNotification的使用(对观察者模式最通俗、易懂的讲解)

这是一个观察者模式。

首先在你需要监听的类中加入观察者:

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;

这个观察者在监听到anObject发送名字为aName的notification时,调用selector的方法,在aSelector方法中得到userInfo。
anObject表示从谁那儿发送出来的消息。

比如:

[[NSNotificationCenterdefaultCenteraddObserver:selfselector:@selector(onWebClose)name:@"WebClose"object:nil];

也就是说监听到了object:nil发出消息,消息的名字是WebClose,此时observer就调用onWebClose方法。

如果object:nil表示以广播方式发消息或者得到消息,这个时候只要消息名字是对的就可以得到这个消息。

然后在被监听的类中发送通知:

 

[[NSNotificationCenterdefaultCenterpostNotificationName:@"WebClose"object:nil];

这样观察者就接到了消息会调用selector方法;

最后记得移除这个观察者:

 

[[NSNotificationCenterdefaultCenterremoveObject:self];

这个的好处是:完全两个不相干的view可以建立起来联系;

 

例子代码:http://blog.csdn.net/sqc3375177/article/details/9466687

第一步:
创建2个NSNotificationCenter监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:)
name:UIApplicationWillResignActiveNotificationobject:nil];//监听是否触发home键挂起程序.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:)
name:UIApplicationDidBecomeActiveNotificationobject:nil];//监听是否重新进入程序程序.
第二步:
实现2个NSNotificationCenter所触发的事件方法
-(void)applicationWillResignActive:(NSNotification*)notification

{
    printf("按理说是触发home按下\n");
}

-(void)applicationDidBecomeActive:(NSNotification*)notification
{
    printf("按理说是重新进来后响应\n");
}
注: 在home键触发后,AppDelegate响应的方法为:

-(void)applicationDidEnterBackground:(UIApplication*)application

{ /* Use this method to release shared resources, save user data, invalidate timers,

and store enough application state information to restore your application to its current state in case it is terminated later. If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. */

}

 

 

 

posted @ 2014-03-12 14:59  ygm900  阅读(2547)  评论(0编辑  收藏  举报