Krumelur
Krumelur

Reputation: 33048

NSTimer versus separate thread - which one to choose?

Let's assume we have simple UI and for whatever reason, every 5 seconds a UILabel needs to be updated.

I can now either setup an NSTimer which does the job, or create a separate thread which runs endlessly, sleeps 5 seconds, does its thing, sleeps again and so on.

Which one would I choose to go for? What are the differences?

Upvotes: 1

Views: 537

Answers (3)

JeremyP
JeremyP

Reputation: 86651

Use NSTimer.

Why?

  1. As soon as you introduce extra threads, you introduce the possibility of a whole new class of bugs i.e. thread synchronisation issues. These tend to be very hard to diagnose and resolve due to their indeterminate nature.
  2. You have to do UI updates on the main thread anyway. So your thread would have to do -performSelectorOnMainThread:withObject:waitUntilDone: to update the UI.

If the calculations for the label take a while (don't just assume they do, try it the simple way first and see), have your timer kick off an NSOperation to do the calculations and then have the NSOperations call -performSelectorOnMainThread:withObject:waitUntilDone: when it has finished.

Upvotes: 1

Itai Ferber
Itai Ferber

Reputation: 29833

The UI can only be updated on the main thread of any program. If you want to do calculations for the label in a separate thread, that's perfectly fine, but the code to update your UI will have to operate on the main thread (or, you can use performSelectorOnMainThread:withObject:waitUntilDone: to call setText: on your label and have it operate correctly).

Upvotes: 1

Luke Mcneice
Luke Mcneice

Reputation: 2720

You have to do UI operations on the main thread anyway, so unless your doing some processing prior to setting the label there would be no benefit of using another thread.

Upvotes: 1

Related Questions