NSNotificationCenter--用法例子

以前做键盘处理时,用到过键盘的通知,现在想要处理一下,当程序从后台进入前台时,能否也有一个类似的通知呢,这样对于各页面的处理都比较方便了,研究了一下,找到了一个类似的解决办法,使用NSNotificationCenter 。 其实NSNotificationCenter的使用还是挺简单的。 下面以我的程序中从后台进入前台时,通知某些页面进行刷新为例。 1. 在程序从后台进入前台时发送一个通知。(这个函数在AppDelegate里)
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    //发送程序进入前台的通知
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    NSLog(@"Sending notification");
}
2. 在需要响应该这一通知的页面内,添加对于这个通知的注册
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
           //注册通知
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc addObserver:self
           selector:@selector(applicationWillEnterForeground:)
               name:@"applicationWillEnterForeground"
             object:nil];
    NSLog(@"Registered with notification center");
    }
    return self;
}
3. 释放通知  (在该页面销毁时,注意:千万不要忘记,否则将多次响应该通知的内容
-(void)dealloc
{
    //释放通知
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc removeObserver:self];
    [super dealloc];
}
4.执行该通知的函数  这就是你要执行的事件的函数时,比如,我需要刷新这个页面。
- (void)applicationWillEnterForeground:(NSNotification *)note
{
 //       [self reloadPage];
 }
  好了,这样一个通知就做好,还是比较容易的。其实,这就是我们经常用到的观察者模式,也许在学习各种模式时,并不是很清楚,这东西该如何使用,看了这样的例子,我自己也清楚了一些了。    

posted on 2013-02-16 14:59  流れ星ーー  阅读(322)  评论(0编辑  收藏  举报

导航