【问题标题】:GCD ERROR :Tried to obtain the web lock from a thread other than the main thread or the web threadGCD ERROR : 试图从主线程或 web 线程以外的线程获取 web lock
【发布时间】:2014-01-03 10:29:27
【问题描述】:

我的代码:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *prePath = [[spineArray objectAtIndex:spineIndex - 1] spinePath];
        NSURL *preURL = [NSURL fileURLWithPath:prePath];
        UIWebView *tmpWebView = [self createWebView:preURL];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.preWebView = tmpWebView;
        });

});

- (UIWebView *)createWebView:(NSURL *)url
{
UIWebView *tmpWebView = [[[UIWebView alloc] initWithFrame:CGRectMake(0, 0,kRootViewWidth, kRootViewHeight)] autorelease];
tmpWebView.delegate = self;
[tmpWebView setBackgroundColor:[UIColor whiteColor]];


currentTextSize = 100;

UISwipeGestureRecognizer *rightSwipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(gotoNextPage)];
[rightSwipeRecognizer setDirection:UISwipeGestureRecognizerDirectionLeft];

UISwipeGestureRecognizer *leftSwipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(gotoPrevPage)];
[leftSwipeRecognizer setDirection:UISwipeGestureRecognizerDirectionRight];

[tmpWebView addGestureRecognizer:rightSwipeRecognizer];
[tmpWebView addGestureRecognizer:leftSwipeRecognizer];

[rightSwipeRecognizer release];
[leftSwipeRecognizer release];

[tmpWebView loadRequest:[NSURLRequest requestWithURL:url]];
return tmpWebView;

}

我们运行的时候,提示错误是:

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

【问题讨论】:

    标签: ios multithreading


    【解决方案1】:

    您的错误确切地告诉您您的问题是什么This may be a result of calling to UIKit from a secondary thread. 在您的 createWebView 方法中,您调用了 UIKit。当您不在主线程上运行并且在此代码示例中您从另一个线程调用该方法时,这是不允许的。

    为什么不将对该方法的调用移到主线程上的调度中?

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *prePath = [[spineArray objectAtIndex:spineIndex - 1] spinePath];
        NSURL *preURL = [NSURL fileURLWithPath:prePath];
        dispatch_async(dispatch_get_main_queue(), ^{
            UIWebView *tmpWebView = [self createWebView:preURL];
            self.preWebView = tmpWebView;
        });
    
    });
    

    【讨论】:

    • 因为耗时任务是:UIWebView *tmpWebView = [self createWebView:preURL];如果我把它放在主线程上,我想我什至不需要多线程。而且我的 createWebView 方法不会更新 UI。
    • 该方法的哪一部分使其耗时? loadRequest:是异步的
    • 哦,是的。所以我不需要使用gcd?
    • 谢谢。我不会使用 gcd。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    • 1970-01-01
    • 2012-12-31
    • 1970-01-01
    相关资源
    最近更新 更多