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?
2 Solutions Collect From Internet About “What is a runloop?”
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.
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.
- How do I specify an iPad Retina icon in XCode 4.3 for an iPhone-only app?
- Add another button next to the “back” button on the left of a UINavigationBar
- What's the cleanest way of applying map() to a dictionary in Swift?
- Change map type of an MKMapView
- ShareKit Compile Issue – JSONKit not found
- Redefinition with a different type
- Get the type of AnyObject dynamically in Swift
- Button changes title every time pressed
- Upload photo with UIWebView
- Create a standalone view in storyboard to use programatically
- Given a view, how do I get its viewController?
- Undo/Redo for drawing in iOS
- Why do Xcode templates have #imports that duplicate Prefix.pch?
- Upload video on youtube from iphone app
- NSPredicate crash after swift 3 migration