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的实例变量。 app
Observing 一个已经deallocate的对象不会引发程序crash,可是notifying 一个已经deallocated 的observer会引发程序的crash。这就是为何要在dealloc 中加入removeObserver:。因此addObserver与 removeObserver必定要成对出现。通常状况下,在init方法中开始observing, 在dealloc中结束observing。 post
-(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]; } }