Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

iphone - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...