简体   繁体   English

NSNotification-如何防止意外崩溃?

[英]NSNotification - how to prevent unexpected crashes?

In my app I have a few VCs that need to receive NSNotifications from my model, which is fetching data asynchronously. 在我的应用程序中,我有一些VC需要从我的模型中接收NSNotifications,该模型是异步获取数据的。 The problem is that the VCs disappear from time to time and when the model finishes fetching data and tries to send a notification to a VC that is already gone, the app crashes. 问题在于,VC有时会消失,并且当模型完成数据获取并尝试向已消失的VC发送通知时,应用程序将崩溃。 Is there an option to prevent this crashing? 有防止这种崩溃的选项吗? Like telling NSNotificationCenter "it's ok if the observer is not there"? 就像告诉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];

Apple Documentation : 苹果文档

Be sure to invoke this method (removeObserver: or removeObserver:name:object:) before notificationObserver or any object specified in addObserver:selector:name:object: is deallocated. 确保在取消分配NotificationObserver或addObserver:selector:name:object:中指定的任何对象之前,调用此方法(removeObserver:或removeObserver:name:object :)。

add the removeObserver call to dealloc of observer. 将removeObserver调用添加到观察者的dealloc。

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

我认为,您只需要执行以下操作:

[[NSNotificationCenter defaultCenter] removeObserver:self ];

You have to call NSNotificationCenter removeObserver... for each time you call addObserver... . 每次调用addObserver...时,都必须调用NSNotificationCenter removeObserver... This is typically done in the dealloc method. 这通常是在dealloc方法中完成的。

To be honest, with this approach you are mitigating the symptoms rather than curing the disease. 老实说,使用这种方法可以缓解症状,而不是治愈疾病。

If you are using an asynchronous networking library such as AFNetworking to return NSOperation instances, then you would be better to manage these in an NSOperationQueue . 如果您使用诸如AFNetworking之类的异步网络库返回NSOperation实例,那么最好在NSOperationQueue管理这些NSOperationQueue Then, when your controller is popped, in the viewWillDisappear method, cancel all outstanding asynchronous requests: 然后,在弹出控制器时,在viewWillDisappear方法中,取消所有未完成的异步请求:

[myOpQueue cancelAllOperations];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM