我使用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中得到错误?

最佳答案

问题是,在取消分配对象时,必须将其作为观察者删除:

[[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:

关于ios - NSNotification-观察者不匹配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16674222/

10-13 09:25