0

我使用 NSNotificationCenter:

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

和发布:

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

其中 self 是@interface MyPlayer : NSObject

当我调用它时,它在大多数情况下都很好用,但是当我释放并分配回 MyPlayer 实例时,我收到了这个错误:

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

我怎么可能从 UIView 收到错误?

4

2 回答 2

2

您必须在 dealloc 中删除观察者:

[[NSNotificationCenter defaultCenter] removeObserver:self]
于 2013-05-21T15:54:37.690 回答
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:
于 2013-05-21T15:58:00.293 回答