Andrew
Andrew

Reputation: 16051

How do I prepare my UI in a background thread?

A UIViewController takes about half a second to load its contents and appear on screen. How can I make them all load in the background and appear when they're ready?

Upvotes: 1

Views: 3495

Answers (4)

Jody Hagins
Jody Hagins

Reputation: 28419

Create a GCD queue to process your work in a background thread (read the docs, because my "create" label and options may not be what you want).

You send it to the queue asynchronously, meaning that the call to dispatch_async will make appropriate arrangements for the block of code you give it to run in another thread and it will then return back to you "immediately."

All the work in the block you give it will be executed on a separate thread. Note, at the end, you do another call, this time with the well know main queue. This arranges for that code to run in the main thread, which is mandatory for any UI work.

Also, you really should read the documentation on GCD and especially blocks, because there are memory and cycle considerations. Good luck.

dispatch_queue_t workQ = dispatch_queue_create("bgWorkQ", 0);
dispatch_async(workQ, ^{
    // This code is now running in a background thread.
    // Do all your loading here...
    // When ready to touch the UI, you must do that in the main thread...
    disptach_async(dispatch_get_main_queue(), ^{
        // Now, this code is running in the main thread.
        // Update your UI...
    });
});
dispatch_release(workQ);

Upvotes: 1

kaar3k
kaar3k

Reputation: 994

A Background Thread cant update the UI,you can perform all the processing logic in background thread and call the main thread for UI update

Example to load a tableView with Data ,use the background thread to process everything and load the Data, call [tableView reloadData] using the main thread, see Grand central Dispatching to know how to Work with Threads in IOS..

Hope it Helps

Upvotes: 1

Abizern
Abizern

Reputation: 150785

There is a LazyTableImages sample on the Apple developer site.

It shows how to perform the heavy lifting in a background thread and update the UI on the main thread.

PerformSelectorInBackground:withObject: is a possible solution, although a more modern method would be to use asynchronous blocks. You can run code on the main thread from within these blocks to update the UI Safely.

The Concurrency Programming Guide is a good place to find more information and examples of this.

Upvotes: 2

Ryan Poolos
Ryan Poolos

Reputation: 18561

The easiest way is to use NSObject's - (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg You just pass it a selector and it will happy in the background and not block your UI. Be aware however that there are rules to background threads.

You shouldn't update your UI from the background thread. And you need to make sure the methods you're calling are thread safe.

Upvotes: 0

Related Questions