Question

I'm making a CLI tool for Mac OS X, my main looks something like this:

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

    @autoreleasepool {

        //Some startup stuff here
        [ServerPool sharedPool]; //Start the pool

        /*
         UI stuff for cli version
         */
        while (1){
            [[CLIUI sharedCLI] mainMenu];
            [[CLIUI sharedCLI] menuInput];
        }

    }
    return 0;
}

and in another section of the code I am starting a NSTimer

progressUpdateTimer = [NSTimer timerWithTimeInterval:1.0
                                              target:self
                                            selector:@selector(updateProgress:)
                                            userInfo:nil
                                             repeats:YES];

[[NSRunLoop currentRunLoop] addTimer: progressUpdateTimer forMode:NSDefaultRunLoopMode];

However, it never fires the selector updateProgress:. I believe this is because I do not have an NSRunLoop established in my main, what would be the proper fix for this?

Was it helpful?

Solution

Timers and anything else dependent on the run loop won't fire unless the run loop is running.

In a command line program, you'd ideally use dispatch_main() and pass control to GCD or you run the [NSThread currentRunLoop] in an appropriate mode for an appropriate amount of time.

You're gonna have to get rid of that while(1) as it'll block the run loop.

The concurrent programming documentation has extensive documentation on how to use run loops.

If you really need that while loop, move it to a second thread (an NSRunLoop on the main thread is a lot easier to deal with) and run the run loop on the main thread.


You'll need to replace that while(1) loop with an NSRunLoop. Which also likely means that you'll need to change your input code to be either a dispatch_source or an NSFileHandle that is reading from stdin, etc...

I.e. you are going to have to refactor your code quite a bit. Do a google search for something like "using nsrunloop in a command line program" and you'll likely get quite a few hints. As well, the NSRunLoop documentation points to a bunch of examples.

It may seem daunting, but once you grok NSRunLoops they are amazingly powerful constructs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top