NSNotification - 观察者不匹配

时间:2013-05-21 15:50:13

标签: ios objective-c notifications nsnotificationcenter

我使用NSNotificationCenter:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playNow:) name:@"PlayNow" object:nil];

和发布:

[[NSNotificationCenter defaultCenter] postNotificationName:@"PlayNow" object:nil userInfo:noteInfoDictionary];

其中self是@interface MyPlayer : NSObject

的实例

当我调用它时,大多数情况都很好用,但是当我dealloc并重新分配MyPlayer实例时,我收到了这个错误:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView playNow:]: unrecognized selector sent to instance 0x8929150'

我怎么可能从UIView那里得到错误?

2 个答案:

答案 0 :(得分:2)

你必须删除dealloc中的观察者:

[[NSNotificationCenter defaultCenter] removeObserver:self]

答案 1 :(得分:1)

问题是你必须在释放它时将对象作为观察者删除:

[[NSNotificationCenter defaultCenter] removeObserver:self]

这是因为当dealloc / init另一个对象时,“playNow”方法被调用到解除分配的实例:

MyPlayer[1] init
MyPlayer[1] addObserver
MyPlayer[1] dealloc

MyPlayer[2] init
MyPlayer[2] addObserver

< POST NOTIFICATION >

通知将同时调用:

MyPlayer[1] playNow:    <-- It is causing you the error, because is deallocated
MyPlayer[2] playNow: