UIWebView在多线程ViewController中

UIWebView在多线程ViewController中

问题描述:

我在viewcontroller中有一个UIWebView,它有两个方法如下。问题是如果我在第二个线程完成之前弹出(在导航栏上点击回退)此控制器,应用程序将在[super dealloc]后崩溃,因为试图从主线程之外的线程获取Web锁定,这可能是从辅助线程调用UIKit的结果。任何帮助将非常感激。

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


一个后台线程是最后一个版本,导致视图控制器的dealloc在后台线程中发生在同一个崩溃。

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.

上面的 [self retain] autorelease] 仍然会导致最后的版本发生在后台线程的自动释放池。 (除非有关于从自动释放池释放的特别的东西,我惊讶这会产生影响)。

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