user
user

Reputation: 3456

When should a task be executed asynchronously vs on the main thread?

I understand that all changes to the views should be on the main thread, but at what level of complexity should I start to consider using dispatch_async?

Should it be used for: - number crunching (like computing a complex probability) - saving to some form of persistent storage - updating a model object - initializing bulky objects

I'm comfortable with iOS until it comes to threading. I always do asynchronous network requests, but aside from that I just try to use minimal resources on the main thread and that still makes for a slightly laggy app.

I searched multiple sources for this so if there is a similar question, point it out and forgive my ignorance.

Upvotes: 1

Views: 135

Answers (3)

Rob
Rob

Reputation: 437432

Most things that are not UI-related, but might adversely affect the responsiveness of your app, are all candidates for tasks to be moved to the background queue. Don't worry about not being comfortable yet, but some of these resources might help:

Upvotes: 3

Costique
Costique

Reputation: 23722

Profile your app. Seriously, nothing else will tell you where exactly your app becomes laggy. I've seen unexpected bottlenecks like UILabel rendering and string processing in my own code. Without Instruments I would never even consider optimizing them.

Upvotes: 1

Reinhard Männer
Reinhard Männer

Reputation: 15217

A very simple answer: The device should be responsive, i.e. react to user interactions as far as possible immediately. Thus any operation that takes more than a fraction of a second should be executed as a separate thread, whenever possible.
Of course multithreading can be tricky, but if the threads are well separated, it is rather straightforward. The most important thing one has to keep in mind is that most classes of the UIKit, and many other classes like arrays are not thread-safe, and accessing them from multiple threads must be synchronized, e.g. by using a @synchronize block. So, read the docs, e.g. here, carefully.

Upvotes: 2

Related Questions