Pecans
Pecans

Reputation: 163

Objective-C: How to stop a NSTimer?

how would i go about stopping my timer whenever I try to do [myTimer invalidate]; I get an error.

My Timer:

    NSTimer *MyTimer;
MyTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0
                                         target: self
                                       selector: @selector(handleTimer)
                                       userInfo: nil
                                        repeats: YES];

Here's the if statement I have set up for the timer.

-(void)handleTimer{

if (count >= 0) {
    [secondsLeft setText:[NSString stringWithFormat:@"%ld",(long)count]]; //displays current value of count to UI
    count--; //Incrementally decreases count
} else if(count <= 0) { //if the timer runs out then...
self.secondsLeft.text = @"Times's Up!";
    [answerButtonOutlet setEnabled:NO];
    self.secondsLeftToAnswer.text = @"Answer is 30";
} else if([self.secondsLeftToAnswer.text isEqual: @"Correct!"]) { //else if statement if user gets answer Correct.
    [myTimer invalidate]; // error occurs here. "Unknown receiver 'myTimer': did you mean NSTimer?
}

    }

How would I make it so that I don't get the error in the second else if statement? I'm brand new to coding so I'm sure its probably pretty obvious but I can't figure it out for the life of me. Thanks!

Upvotes: 0

Views: 185

Answers (3)

Henry F
Henry F

Reputation: 4980

You have [myTimer invalidate], when you should really have:

[MyTimer invalidate];
MyTimer = nil;

Try this change and let me know what happens. Also, throw an NSLog in that else if to make sure it's firing.

Upvotes: 0

user3386109
user3386109

Reputation: 34829

You're better off just using the timer argument that gets passed to the handler method. In other words, you need an extra colon in the selector to indicate that the handler takes an argument

selector: @selector(handleTimer:)   // note the colon at the end

Then your handler looks like this

-(void)handleTimer:(NSTimer *)theTimer 
{
    ...

    else if([self.secondsLeftToAnswer.text isEqual: @"Correct!"]) { 
        [theTimer invalidate];
    }
}

Upvotes: 1

Kyle Emmanuel
Kyle Emmanuel

Reputation: 2221

Since NSTimer *MyTimer;

[myTimer invalidate]; should be [MyTimer invalidate];

Upvotes: 1

Related Questions