2013-05-21 58 views
0

我用NSNotificationCenter:NSNotification - 觀察者不匹配

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

和郵政業:

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

其中自是@interface MyPlayer : NSObject

例如當我把它與大多數情況下的偉大工程,但是當我dealloc和撥回MyPlayer實例我得到這個錯誤:

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

如何從UIView中獲取錯誤?

+0

您是否在刪除dealloc中的觀察者?如果沒有,你應該。 – rdelmar

+0

是的,這是問題所在。 – Kuba

回答

1

的問題是,你必須在你的dealloc它刪除對象作爲觀察員:

[[NSNotificationCenter defaultCenter] removeObserver:self] 

這是因爲當dealloc的/初始化另一個對象,將「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: 
2

您必須刪除觀察者的dealloc:

[[NSNotificationCenter defaultCenter] removeObserver:self]