iphoneobjective-cnstimeruiapplicationcfrunloop

NSTimer doesn't work without UIApplication?


I have a custom iPhone application which doesn't rely on UIKit in any way (it is not linked to UIKit). This means that I'm not using UIApplication and therefore not calling UIApplicationMain.

The problem is that when I create a timer it never fires. The timer is created like that:

[NSTimer timerWithTimeInterval:10 target:self selector:@selector(updateTime) userInfo:nil repeats:TRUE];

I am suspecting that the problem might be run-loop related as after I finish basic initialization in "main()" , I do this:

NSLog(@"Starting application ...");
applicationInstance = [MyApp alloc];
[applicationInstance setMainLayer:mainLayer];
[NSThread detachNewThreadSelector:@selector(runApplication) toTarget:applicationInstance withObject:nil];

CFRunLoopRun();

I reverse-engineered UIKit and noticed that UIApplication does much more things like registering for system events etc. NSTimer might be relying on one of those things. The other thing I've noticed is that in UIApplication's delegate the thread is the same as in main().

How do I get NSTimer to work properly? If it is run-loop related, can someone point out the error? "CFRunLoopRun()" is used to hang up the main thread so the rest of the application can run. I don't think it is right though.

Edit: I think the run loop needs to be configred. Somehow ...


Solution

  • Your problem is definitely run loop-related; see the NSTimer reference, specifically, the introduction:

    Timers work in conjunction with run loops. To use a timer effectively, you should be aware of how run loops operate—see NSRunLoop and Threading Programming Guide. Note in particular that run loops retain their timers, so you can release a timer after you have added it to a run loop.