Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

     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?

like image 948
Huang Avatar asked Feb 24 '13 06:02

Huang


2 Answers

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.

like image 115
Florian Avatar answered Sep 18 '22 12:09

Florian


Most UIKit objects, including instances of UIView, must be manipulated only from the main thread/queue. You cannot send messages to a UIView on any other thread or queue. This also means you cannot create them on any other thread or queue.

like image 34
rob mayoff Avatar answered Sep 18 '22 12:09

rob mayoff