Daniel Klöck
Daniel Klöck

Reputation: 21157

NSTimer selector calling

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.

Upvotes: 0

Views: 1012

Answers (1)

deanWombourne
deanWombourne

Reputation: 38485

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.

Upvotes: 2

Related Questions