views:

33

answers:

1

Can someone explain to me how exactly the NSTimer behavior is?

Basically I want to know if there is a way to always have the NSTimer event happen. Event if there is currently something executing.

For example, in:

NSTimer* testTimer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(testMethod) userInfo:nil repeats: NO];
for (int i=0; i<9999; i++) {
    NSLog(@"%i", i);
}

testMethod will never be executed since the for loop is being executed when the event fires.

+2  A: 

When the timer fires, it's selector is added to the run loop to be executed as soon as possible.

However, you're creating a loop so the run loop never gets a change to do the timer's selector resulting in what you're seeing - the app waits for the loop to finish before running your timer's selector.

If you have a long running task, it's best to put it into a new thread - try looking at performSelectorInBackground and reading up on threading in objective-c.

deanWombourne
It's often much simpler to simply make another timer for this loop, performing one iteration every time the timer fires. Or, nowadays, you could use an operation queue or dispatch queue instead—essentially the same thing, but potentially parallel. Any threaded solution (including an operation queue or the main dispatch queue) will bring a lot of potential headaches that just making another timer on the main thread wouldn't.
Peter Hosey
Agreed - if you're trying to run a little task many times, definitely avoid threads! If it's one long running task, you've just got to bite the bullet and learn about threading :(
deanWombourne