Rich
Rich

Reputation: 154

NSTimer firing instantly

I'm trying to develop a game and running into a small issue with NSTimer, once a sprite appear it has a certain amount on time in my scene before fading out.

double CALC_TIME = 5;
[NSTimer scheduledTimerWithTimeInterval:CALC_TIME target:self selector:@selector(hideSprite) userInfo:nil repeats:NO];

I want hideSprite to be called after 5 seconds, but instead it's called instantly(Or near instant).

A possible solution: I know I could do this by setting the timer to repeat, and having a bool firstCall that is set first time and then the next interval the fading is done, the timer is invalidated but I don't think this is good practice

Like this:

bool firstCall = false;
-(void)hideSprite{
        if(!firstCall){
        firstCall = true
    }else{
        //fade out sprite
        //Invalidate NSTimer
        //firstCall = false;
    }
}

Thanks for your help!

Upvotes: 3

Views: 2967

Answers (3)

Tim
Tim

Reputation: 5054

I suspect something else is calling hideSprite. The code you have written will cause the timer to wait for five seconds before calling the selector hideSprite.

Provide a different selector (write a new test method which just does an NSLog) to the timer and see what happens. This will tell you a) whether the timer is indeed immediately firing and b) if something else is calling hideSprite.

[NSTimer scheduledTimerWithTimeInterval:CALC_TIME target:self selector:@selector(testTimer) userInfo:nil repeats:NO];

-(void) testTimer { NSLog(@"Timer - and only the timer - called me."); }
-(void) hideSprite {
    NSLog(@"I definitely wasn't called by the timer.");
}

Upvotes: 2

David Dunham
David Dunham

Reputation: 8329

Quite often it's easier to just use something like

[UIView animateWithDuration: 0 delay: 5 options:0 animations: nil completion:
^{
  // fade sprite
}];

(not sure if animations can be nil, but you get the idea).

Upvotes: 1

Jeremy
Jeremy

Reputation: 9030

Consider initializing your timer using the initWithFireDate:interval:target:selector:userInfo:repeats method. Here is a more detailed look at NSTimer.

Upvotes: 0

Related Questions