[英]How to register an object (that isn't a view controller) as a Notification Center observer
[英]View controller is not removing Notification Center observer
我有這個viewDidLoad
代碼:
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] removeObserver:self];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(messageReceived:)
name:@"messageReceived"
object:nil];
}
該視圖控制器是UITabBarController
。 每次我轉到其選項卡時,都會調用viewDidLoad
,但似乎[[NSNotificationCenter defaultCenter] removeObserver:self];
不執行任何操作,並且每次調用該方法時都會注冊“ messageReceived”。
來自另一個類的以下代碼片段通知:
[[NSNotificationCenter defaultCenter] postNotificationName:@"messageReceived"
object:nil
userInfo:nil];
僅被調用一次,但是,例如,如果我轉到觀察的視圖控制器的選項卡3次,並且viewDidLoad
被調用3次,則其messageReceived:
方法也被調用3次...
我可能會缺少什么?
您可能想鈎住以下內容:
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(messageReceived:)
name:@"messageReceived"
object:nil];
}
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
當您點擊選項卡欄時,將創建UIViewController的新實例,因此將調用viewDidLoad
。 當您從viewDidLoad
內調用removeObserver
方法時,您要從觀察者中刪除新創建的視圖控制器,此時觀察者從未注冊。
-viewWillDisappear
在將視圖控制器從視圖層次結構中刪除之前被調用,因此從該方法調用removeObserver
應該可以解決問題。
祝好運!
我認為您應該在dealloc方法中添加“刪除觀察者”代碼,該代碼將在刪除視圖時由arc自動調用,同時還為進行后台處理,您可以通過應用程序委托方法“ applicationWillEnterInBackground”和其他方法發布通知。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.