Creating UIViews in a background thread

I know that the user interface should only be updated in the main thread, but is it possible to create and add subviews to a separate thread if they are not added to the visible view? Will it cause memory and performance issues? Here is a sample 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]; }]; }]; }]; 
+4
source share
2 answers

My understanding of why you don't want to do this is that CALayer backed up by memory, which is not thread safe. This way you can draw a background stream but not render layers or manipulate views.

So what you do is draw a complex presentation logic in the context of the image and transfer the image to the main stream, which will be displayed as an image.

Hope this helps!

+3
source

Changes in the user interface of the secondary stream will cause the application to crash. Therefore, always make user interface changes in the main thread.

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

All Articles