1Poster.h 2 3//定义一个string常量,用于notification 4 5extern NSString * const PosterDidSomethingNotification; 6 7//与extern const NSString *PosterDidSomethingNotification 的区别 8 9//前者是一个指向immutable string的常量指针。后者是一个指向immutable string的可变指针。 10 11Poster.m 12 13NSString *const PosterDidSomethingNotification = @"PosterDidSomethingNotification"; 14 15... 16 17//在notification 中包含 poster 18 19[[NSNotificationCenter defaultCenter] postNotificationName:PosterDidSomethingNotification 20 21 object:self]; 22 23Observer.m 24 25//import Poster.h 26 27#import "Poster.h" 28 29... 30 31//注册可以接受的notification 32 33[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(posterDidSomething:) 34 35 name:PosterDidSomethingNotification object:nil]; 36 37... 38 39-(void) posterDidSomething:(NSNotification *)note{ 40 41 //处理notification 42 43} 44 45-(void)dealloc{ 46 47 //一定要删除observations 48 49 [[NSNotificationCenter defaultCenter] removeObserver:self]; 50 51 [super dealloc]; 52 53}
Observer 应该认真考虑是应该observe一个特定对象还是nil(指定名称的所有notifications,而不管object的值)。如果observe一个特定的实例,这个实例应该是retain的实例变量。
Observing 一个已经deallocate的对象不会引起程序crash,但是notifying 一个已经deallocated 的observer会引起程序的crash。这就是为什么要在dealloc 中加入removeObserver:。所以addObserver与 removeObserver一定要成对出现。一般情况下,在init方法中开始observing, 在dealloc中结束observing。
1-(void)setPoster:(Poster *)aPoster{ 2 3NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 4 5if (_poster != nil){ 6 7 //删掉所有旧值的oberservations 8 9 [nc removeObserver:self name:nil object:_poster]; 10 11 //nil 意味着“any object” 或者"any notification" 12 13 _poster = aPoster; 14 15 if (_poster != nil){ 16 17 [nc addObserver:self selector:@selector(anEventDidHappen:) name:PosterDidSomthingNotification object:_poster]; 18 19 } 20 21}