cannyboy
cannyboy

Reputation: 24416

Building up UIViews on background thread

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];
        }];
    }];
}];

Upvotes: 4

Views: 1803

Answers (2)

Carl Veazey
Carl Veazey

Reputation: 18363

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!

Upvotes: 3

Rajneesh071
Rajneesh071

Reputation: 31081

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];

Upvotes: 2

Related Questions