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

前端 未结 3 1424
我寻月下人不归
我寻月下人不归 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:09

    As rob said the UI changes should be done only on main thread.You are trying to add from a secondary thread.Change your code [self.view addSubview:webView]; to

    [self.view performSelectorOnMainThread:@selector(addSubview:) withObject:webView waitUntilDone:YES];

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-11 11:22

    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.

    0 讨论(0)
提交回复
热议问题