iphone - 多线程 ViewController 中的 UIWebView

标签 iphone objective-c cocoa-touch memory-management uikit

我在 View Controller 中有一个 UIWebView,它有以下两种方法。问题是如果我在第二个线程完成之前弹出(在导航栏上返回)这个 Controller ,应用程序将在 [super dealloc] 之后崩溃,因为“试图从主线程以外的线程获取网络锁或Web 线程。这可能是从辅助线程调用 UIKit 的结果。”。非常感谢任何帮助。

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

最佳答案

我有相同的解决方案,其中后台线程是最后一个版本,导致 View Controller 的 dealloc 发生在后台线程中,最终导致相同的崩溃。

上面的 [[self retain] autorelease] 仍然会导致最终释放发生在后台线程的自动释放池中。 (除非自动释放池中的释放有什么特别之处,否则我很惊讶这会有所作为)。

我发现这是我理想的解决方案,将这段代码放入我的 View Controller 类中:

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

这确保了我的 View Controller 类的release 方法总是在主线程上执行。

令我有点惊讶的是,某些只能从主线程正确释放的对象还没有内置这样的东西。哦,好吧......

关于iphone - 多线程 ViewController 中的 UIWebView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/945082/

相关文章:

objective-c - 如何停止 NSInvocationOperation?

ios - 应用程序处于后台模式时的文本转语音功能?

ios - 使用 Core Animation 的循环、可逆动画

iphone - XCode 4 在尝试运行项目时显示 "Argument Invalid"

iphone - TableView 为每个 View 添加相同的功能

ios - UITableViewCell 中 UIVisualEffectView 的性能问题

iphone - 基本货币转换应用程序

ios - AVAssetWriterInput appendSampleBuffer 成功,但从 CMSampleBufferGetSampleSize 记录错误 kCMSampleBufferError_BufferHasNoSampleSizes

iphone - 在 iPhone OS 上,如何以编程方式检查地址簿中是否存在联系人?

objective-c - Objective-C 属性的默认属性是什么?