繁体   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