views:

68

answers:

2

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

+3  A: 

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.

Shaggy Frog
So how do I get it to work? I am really confused right now
Nick Brooks
Did you check out the Threaded Programming Guide? The section on "Using Run Loops"? I haven't created my own Run Loop before, but that seems to me to be a good place to start!
Shaggy Frog
Yes, I did. It didn't provide any info :(
Nick Brooks
"Listing 3-1 Creating a run loop observer" is exactly what you're trying to do -- create a run loop and add an NSTimer -- is it not?
Shaggy Frog
A: 

The solution was pretty simple

NSTimer * timeUpdateTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:TRUE]; 
[[NSRunLoop mainRunLoop] addTimer:timeUpdateTimer forMode:NSDefaultRunLoopMode];

Thanks for the tip Shaggy Frog

Nick Brooks