creating a view on a background thread, adding it the main view on the main thread

前端 未结 3 1447
我寻月下人不归
我寻月下人不归 2021-01-11 10:49

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

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

<         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-11 11:13

    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];
        });
    });
    

    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:

    Threading Considerations

    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.

提交回复
热议问题