UIWebView in multithread ViewController(多线程 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:多线程 ViewController 中的 UIWebView
基础教程推荐
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01