簡體   English   中英

NSNotification-如何防止意外崩潰?

[英]NSNotification - how to prevent unexpected crashes?

在我的應用程序中,我有一些VC需要從我的模型中接收NSNotifications,該模型是異步獲取數據的。 問題在於,VC有時會消失,並且當模型完成數據獲取並嘗試向已消失的VC發送通知時,應用程序將崩潰。 有防止這種崩潰的選項嗎? 就像告訴NSNotificationCenter“觀察員不在那沒關系”?

:)

// Subscribe for notifications
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishedLoading) name:@"Finished Loading" object:nil];

// Model sends a notification to a subscribed VC
[[NSNotificationCenter defaultCenter] postNotificationName:@"Finished Loading" object:nil userInfo:nil];

蘋果文檔

確保在取消分配NotificationObserver或addObserver:selector:name:object:中指定的任何對象之前,調用此方法(removeObserver:或removeObserver:name:object :)。

將removeObserver調用添加到觀察者的dealloc。

- (void)dealloc{
...
[[NSNotificationCenter defaultCenter] removeObserver:self ];
...
}

我認為,您只需要執行以下操作:

[[NSNotificationCenter defaultCenter] removeObserver:self ];

每次調用addObserver...時,都必須調用NSNotificationCenter removeObserver... 這通常是在dealloc方法中完成的。

老實說,使用這種方法可以緩解症狀,而不是治愈疾病。

如果您使用諸如AFNetworking之類的異步網絡庫返回NSOperation實例,那么最好在NSOperationQueue管理這些NSOperationQueue 然后,在彈出控制器時,在viewWillDisappear方法中,取消所有未完成的異步請求:

[myOpQueue cancelAllOperations];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM