Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dealloc on Background Thread

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): 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.

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];
}

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.

like image 617
Mark Brackett Avatar asked Apr 30 '10 16:04

Mark Brackett


2 Answers

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:

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.

like image 199
Gabriele Mondada Avatar answered Oct 11 '22 14:10

Gabriele Mondada


The simple rule is that it's an error to do anything on a UI* from a background thread.

like image 42
David Gelhar Avatar answered Oct 11 '22 15:10

David Gelhar