[NSNotificationCenter defaultCenter] addObserverForName:
这个方法我们一般用收听通知, 这个方法有Block的写法, 代码的可读比使用[NSNotificationCenter defaultCenter] addObserver
更高, 所以我经常使用这个作为接听通知.
如果你在收听完了之后没有将它移出, 那么当你下一次再次调用这个通知后的时候, 收听通知就会执行2次block里面代码, 如果收听多次而没有移除收听的方法, 那么block里面的代码会被多次执行.
同样ViewController将一直不会调用- (void) deallloc
这个方法.
下面示例一个监听通知的方法:
@interface()
@property (nonamic, strong) id observer;
@end
- (void) viewDidLoad {
self.observer = [[NSNotificationCenter defaultCenter]
addObserverForName:MPMoviePlayerPlaybackDidFinishNotification
object:nil
queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
}];
}
- (void) dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self.observer];
self.observer = nil;
}
记住一点要在最后把收听设置为nil, 否则这个收听一致不会被移除..