Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIWebView in multithread ViewController

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 done, the app will crash after [super dealloc], because "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.". Any help would be really appreciated.

-(void)viewDidAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(load) object:nil];
    [operationQueue addOperation:operation];
    [operation release];
}

-(void)load {
    [NSThread sleepForTimeInterval:5];
    [self performSelectorOnMainThread:@selector(done) withObject:nil waitUntilDone:NO];
}
like image 714
Tao Avatar asked Jun 03 '09 14:06

Tao


1 Answers

I had the same solution where a background thread was the last release, causing dealloc of view controller to happen in a background thread ending up with the same crash.

The above [[self retain] autorelease] would still result in the final release happening from the autorelease pool of the background thread. (Unless there's something special about releases from the autorelease pool, I'm surprised this would make a difference).

I found this as my ideal solution, placing this code into my view controller class:

- (oneway void)release
{
    if (![NSThread isMainThread]) {
        [self performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];
    } else {
        [super release];
    }
}

This ensures that the release method of my view controller class is always executed on the main thread.

I'm a little surprised that certain objects which can only be correctly dealloc'ed from the main thread don't already have something like this built in. Oh well...

like image 62
Matt Connolly Avatar answered Sep 18 '22 14:09

Matt Connolly