ios – 在后台线程上创建一个视图,在主线程中添加主视图

我是C的新来的,来自.NET和 java背景.

所以我需要异步地创建一些UIwebviews,我在自己的队列中使用这个

dispatch_queue_t queue = dispatch_queue_create("myqueue",NULL);
     dispatch_async(queue,^{
        // create UIwebview,other things too
             [self.view addSubview:webView];
        });

因为你会想象这会引发错误

bool _WebTryThreadLock(bool),0xa1b8d70: 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...

那么如何在主线程上添加子视图?

解决方法

由于您已经在使用调度队列.我不会使用performSelectorOnMainThread:withObject:waitUntilDone :,而是在主队列上执行子视图添加.
dispatch_queue_t queue = dispatch_queue_create("myqueue",NULL);
dispatch_async(queue,^{
    // create UIwebview,other things too

    // Perform on main thread/queue
    dispatch_async(dispatch_get_main_queue(),^{
        [self.view addSubview:webView];
    });
});

后台队列中实例化UIWebView是很好的.但是要将其添加为子视图,您必须在主线程/队列中.从UIView文档:

线程注意事项

对应用程序的用户界面的操作必须发生在主线程上.因此,您应该总是从在应用程序主线程中运行的代码调用UIView类的方法.唯一可能不是严格必要的时间是创建视图对象本身,但所有其他操作应发生在主线程上.

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...