如何在类文件中创建然后销毁 UIWebView [英] How to create then destroy a UIWebView inside a class file

查看:20
本文介绍了如何在类文件中创建然后销毁 UIWebView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在启动应用程序时在类文件中动态创建一个 UIWebView.

I am trying to dynamically create a UIWebView inside a class file upon launching the application.

我已经成功地在启动时在该类文件中调用了一个函数,但是当我将创建 webview 的代码添加到该函数时,我收到如下错误:试图获取 web从主线程或 Web 线程以外的线程锁定.这可能是从辅助线程调用 UIKit 的结果.现在崩溃..."

I have successfully gotten a function to be called inside that class file upon launching, but when I add the the code to create the webview to that function, I am getting errors like this: "Tried to obtain the web lock from a thread other than the main thread or web thread. This may be the result of calling to UIKit from a secondary thread. Crashing now..."

我创建 UIWebView 的代码是这样的:

My code to create the UIWebView is this:

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 16, 16)];
[webView setDelegate:self];
[webView setHidden:YES];
NSURL *url = [NSURL URLWithString:address];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];

我哪里出错了?

推荐答案

您正在从后台线程创建 webview,这是 Apple 不允许的,并且会使您的应用程序崩溃.
您应该使用 dispatch_async 从主线程创建您的 webview :

You are creating the webview from a background thread, which is not allowed by Apple and makes your app crash.
You should use dispatch_async to create your webview from the main thread :

dispatch_async(dispatch_get_main_queue(), ^{
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 16, 16)];
    [webView setDelegate:self];
    [webView setHidden:YES];
    NSURL *url = [NSURL URLWithString:address];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    [webView loadRequest:urlRequest];   
});

这篇关于如何在类文件中创建然后销毁 UIWebView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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