I have a UIWebView in a viewcontroller, which has two methods as below. The question is if I pop out(tap back on navigation bar) this controller before the second thread is
I currently have a similar problem in my application. A view controller which displays a UIWebView is pushed to a navigation controller and starts a background thread to retrieve data. If you hit the back button before the thread has finished, the application crashes with the same error message.
The problem seems to be that NSThread retains the target (self) and object (argument) and releases it after the method has been run -- unfortunately it releases both from within the thread. So when the controller gets created, the retain count is 1, when the thread is started, the controller gets a retain count of 2. When you pop the controller before the thread is done, the navigation controller releases the controller, which results in a retain count of 1. So far this is fine -- But if the thread finally finishes, NSThread releases the controller, which results in a retain count of 0 and an immediate dealloc from within the thread. This makes the UIWebView (which is released in the dealloc method of the controller) raise that thread warning exception and crash.
I successfully worked around this by using [[self retain] autorelease] as the last statement in the thread (right before the thread releases its pool). This ensures that the controller object is not released immediately but marked as autoreleased and deallocated later in the main thread's run loop. However this is a somewhat dirty hack and I'd rather prefer to find a better solution.