背景线程上的dealloc [英] dealloc on Background Thread

查看:91
本文介绍了背景线程上的dealloc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从后台线程调用 UIViewController 上的 dealloc 是错误的吗?似乎 UITextView (可以?)最终调用 _WebTryThreadLock ,结果是:

Is it an error to call dealloc on a UIViewController from a background thread? It seems that UITextView (can?) eventually call _WebTryThreadLock which results in:


bool _WebTryThreadLock(bool):尝试从主线程或Web线程以外的线程
获取Web锁定。这可能是从辅助线程向UIKit调用
的结果。

bool _WebTryThreadLock(bool): Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread.

背景:我有一个子类 NSOperation 需要一个选择器和一个目标对象来通知。

Background: I have a subclassed NSOperation that takes a selector and a target object to notify.

-(id)initWithTarget:(id)target {
   if (self = [super init]) {
      _target = [target retain];
   }
   return self;
}

-(void)dealloc {
   [_target release];
   [super dealloc];
}

如果 UIViewController NSOperation 开始运行时已被解雇,然后对 release 的调用触发它的 dealloc 在后台线程上。

If the UIViewController has already been dismissed when the NSOperation gets around to running, then the call to release triggers it's dealloc on a background thread.

推荐答案

是的,发布UIViewController是错误的在后台线程(或队列)中。在UIKit中,dealloc不是线程安全的。这在Apple的 TN2109 文档中有明确说明:

Yes, it is an error to make a UIViewController releasing in a background thread (or queue). In UIKit, dealloc is not thread safe. This is explicitly described in Apple's TN2109 doc:


当辅助线程保留目标对象时,必须确保线程在主线程释放其对象的最后一个引用之前释放该引用。如果不这样做,则辅助线程将释放对象的最后一个引用,这意味着对象的-dealloc方法在该辅助线程上运行。如果对象的-dealloc方法执行在辅助线程上不安全的事情,这是有问题的,这对于像视图控制器这样的UIKit对象是常见的。

When a secondary thread retains the target object, you have to ensure that the thread releases that reference before the main thread releases its last reference to the object. If you don't do this, the last reference to the object is released by the secondary thread, which means that the object's -dealloc method runs on that secondary thread. This is problematic if the object's -dealloc method does things that are not safe to do on a secondary thread, something that's common for UIKit objects like a view controller.

这篇关于背景线程上的dealloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆