多线程 ViewController 中的 UIWebView [英] UIWebView in multithread ViewController

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

问题描述

我在视图控制器中有一个 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];
    }
}

这确保了我的视图控制器类的 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...

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

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