问题
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