Understanding NSRunLoop for Target Actions


I’m unclear how the NSRunLoop object is associated with the logger and timer objects in the “timer” example. Based on the example code, we create the logger and timer objects, and then invoke the currentRunLoop for the thread, and tell it to “run”.

So since there doesn’t seem to be an explicit way to link the timer object with the currentRunLoop object, then I assume that activating the NSRunLoop currentLoop object effectively works on any invoked object. When I test that theory by putting the [[NSRunLoop currentRunLoop] run]; statement before invoking the logger and timer options, the program behaves differently (the sayOuch: callback isn’t sent). Why?

[code]#import <Foundation/Foundation.h>
#import “logger.h”

int main (int argc, const char * argv[])

@autoreleasepool {
    [[NSRunLoop currentRunLoop] run];   //<- Why doesn't the sayOouch: callback get sent when this is here?
    Logger *logger = [[Logger alloc] init];
    __unused NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 
return 0;




The method scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: automatically adds the time to the current run loop.


Ok, that makes sense. But I still don’t understand why the [[NSRunLoop currentRunLoop] run] must be invoked after the other objects are created?


The run method never returns. So code after [[NSRunLoop currentRunLoop] run] will never get executed.


Of course! Now I understand. Thanks Aaron! :smiley:


Hi every one,
The run method never returns, so how can the main thead do its UI work?
this makes me confused most when it comes to run loop

thank you