Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I develop Stop Watch Application. In my application, there are Two UIButtons , StartBtn and StopBtn, And also I use NSTimer.

Now, i want to start NSTimer when user click on StartBtn and also stop when your click on StopBtn.

I know that NSTimer is stopped by [MyTimerName invalidate]; method but I don't know how to start NSTimer again?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
475 views
Welcome To Ask or Share your Answers For Others

1 Answer

The NSTimer class is a bit awkward to use; rather than separating the creation/destruction from the start/stop, it's all rolled together. In other words the timer starts as soon as it's created and stops as soon as it's destroyed.

You therefore need to use the existence of the NSTimer object as a flag to indicate if it's running; something like this:

// Private Methods
@interface MyClass ()
{
    NSTimer *_timer;
}
- (void)_timerFired:(NSTimer *)timer;
@end

@implementation MyClass

- (IBAction)startTimer:(id)sender {
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f
                                                  target:self
                                                selector:@selector(_timerFired:)
                                                userInfo:nil
                                                 repeats:YES];
    }
}

- (IBAction)stopTimer:(id)sender {
    if ([_timer isValid]) {
        [_timer invalidate];
    }
    _timer = nil;
}

- (void)_timerFired:(NSTimer *)timer {
    NSLog(@"ping");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...