Building up UIViews on background thread

£可爱£侵袭症+ 提交于 2019-12-23 12:58:14

问题


I'm aware that the UI should only be updated on the main thread, but is it possible to create and add subviews on a separate thread, as long as they are not added to the visible view? Will it cause memory and performance issues? Here's some example code.

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperationWithBlock:^{ 
    // do some fancy calculations, building views
    UIView *aView = ..
    for (int i, i<1000, i++)
    {
        UIView *subView = …
        [aView addSubview:subView];
    }

    // Update UI on Main Thread
    [queue addOperationWithBlock:^{
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{

            // Update the interface
            [self.view addSubview:aView];
        }];
    }];
}];

回答1:


My understanding of why you don't want to do this is that CALayer is backed byy memory that isn't thread safe. So you can draw on a background thread, but not render layers or manipulate views.

So what you do is draw your complex view logic into an image context and pass the image off to the main thread to be displayed in an image view.

Hope this helps!




回答2:


UI changes on secondary thread will cause app crash. So always make UI changes on main thread.

[self performSelectorOnMainThread:@selector(makeUIChanges:) withObject:nil waitUntilDone:YES];


来源:https://stackoverflow.com/questions/12158175/building-up-uiviews-on-background-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!