NSNotification用法简介

Poster.h

//定义一个string常量,用于notification

extern NSString * const PosterDidSomethingNotification;

//与extern const NSString *PosterDidSomethingNotification 的区别

//前者是一个指向immutable string的常量指针。后者是一个指向immutable string的可变指针。

Poster.m

NSString *const PosterDidSomethingNotification = @"PosterDidSomethingNotification";

...

//在notification 中包含 poster

[[NSNotificationCenter defaultCenter] postNotificationName:PosterDidSomethingNotification

                                                                       object:self];

Observer.m

//import Poster.h

#import "Poster.h"

...

//注册可以接受的notification

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(posterDidSomething:)

                                                   name:PosterDidSomethingNotification  object:nil];

...

-(void) posterDidSomething:(NSNotification *)note{

    //处理notification

}

-(void)dealloc{

    //一定要删除observations

    [[NSNotificationCenter defaultCenter] removeObserver:self];

    [super dealloc];

}

Observer 应该认真考虑是应该observe一个特定对象还是nil(指定名称的所有notifications,而不管object的值)。如果observe一个特定的实例,这个实例应该是retain的实例变量。

Observing 一个已经deallocate的对象不会引起程序crash,但是notifying 一个已经deallocated 的observer会引起程序的crash。这就是为什么要在dealloc 中加入removeObserver:。所以addObserver与 removeObserver一定要成对出现。一般情况下,在init方法中开始observing, 在dealloc中结束observing。

-(void)setPoster:(Poster *)aPoster{

NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];

if (_poster != nil){

    //删掉所有旧值的oberservations

    [nc removeObserver:self name:nil object:_poster];

    //nil 意味着“any object” 或者"any notification"

    _poster = aPoster;

    if (_poster != nil){

        [nc addObserver:self selector:@selector(anEventDidHappen:) name:PosterDidSomthingNotification object:_poster];

    }

}

评论

暂无评论