在后台线程上创建一个视图,在主线程上添加主视图 [英] creating a view on a background thread, adding it the main view on the main thread

查看:111
本文介绍了在后台线程上创建一个视图,在主线程上添加主视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to objective C, coming from .NET and java background.

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

So I need to create some UIwebviews asynchronously, I am doing this on my own queue using

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

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

as you owuld imagine this throws an error :

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

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

So how can I add the subview on the main thread?

推荐答案

因为您已经在使用调度队列。我不会使用 performSelectorOnMainThread:withObject:waitUntilDone:,而是在主队列上执行子视图添加。

Since you are already using dispatch queues. I wouldn't use performSelectorOnMainThread:withObject:waitUntilDone:, but rather perform the subview addition on the main queue.

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 文档:

It is fine to instantiate the UIWebView on a background queue. But to add it as a subview you must be on the main thread/queue. From the UIView documentation:

线程注意事项

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

Manipulations to your application’s user interface must occur on the main thread. Thus, you should always call the methods of the UIView class from code running in the main thread of your application. The only time this may not be strictly necessary is when creating the view object itself but all other manipulations should occur on the main thread.

这篇关于在后台线程上创建一个视图,在主线程上添加主视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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