LuckyLuke
LuckyLuke

Reputation: 49107

What is a runloop?

After reading the documentation for NSRunLoop I did not understand very much. I am spawning a secondary thread that has a NSTimer in it that launch every 1sec. Which update a label on the screen with the performSelectorOnMainThread..

However to get it to work I needed a runloop but I do not understand the concept of it?

Anyone who could try to explain it?

Thanks.

Upvotes: 22

Views: 16287

Answers (2)

bbum
bbum

Reputation: 162722

A run loop is effectively:

while(... get an event ...)
    ... handle event ...;

It runs on a thread; the main thread has the main event loop where user events are processed and most UI drawing, etc, occurs. The documentation explains it in detail.

However, in your case, you don't need a thread.

It sounds like all you are doing is periodically updating a label in the UI; something that isn't terribly compute intensive.

Just schedule your timer in the main thread and be done with it. No need for spinning up a thread, using performSelectorOnMainThread:, or incurring all the complexities of guaranteeing data coherency across threads.


Sorry -- didn't understand your question.

Internally, a run loop works by basically putting a flag in the run loop that says "after this amount of time elapses, fire the timer". No additional threads involved and, better yet, it isn't polling to check the time. Think of a run loop as effectively maintaining a timeline. It'll passively let time elapse until there is something of interest found on the timeline (all without polling -- polling sucks. to be avoided.)

It does mean, though, that a Timer will never be 100% accurate. As well, if you have a timer repeating every second, it'll drift over time.

Also; instead of directly triggering a drawing event. Your timer should invalidate the view that needs updating, then let the underlying objects deal with when it is best to actually update the screen.

Upvotes: 33

This page explains it pretty well. FTA:

A run loop is essentially an event-processing loop running on a single thread. You register potential input sources on it, pointing it to the code that it should execute whenever input is available on those sources.

Upvotes: 14

Related Questions