开发者

NSTimer Repeat x times only, then call a selector when it invalidates

开发者 https://www.devze.com 2023-01-06 18:02 出处:网络
Primarily I\'m looking for a way to create an nstimer scheduledTimerWithTimeInterval that repeat开发者_运维技巧s every 3 seconds 10 times then invalidates just as a no-repeating timer would. Is this p

Primarily I'm looking for a way to create an nstimer scheduledTimerWithTimeInterval that repeat开发者_运维技巧s every 3 seconds 10 times then invalidates just as a no-repeating timer would. Is this possible? Ideally an additional selector would fire once the timer invalidates too


Just keep track of the number of loops and keep a reference to the timer object. Then just invalidate it when you've done enough.

// ivars
int loopCount;
NSTimer *myTimer;

// Method that calls your timer.
- (void)doStuff {
    loopCount++;
    if (loopCount >= 10) {
        [myTimer invalidate];
        myTimer = nil;
    } else {

        //do my stuff here...

    }
}

// Method that kicks it all off
- (IBAction)startDoingStuff {
    myTimer = [NSTimer scheduledTimerWithTimeInterval:3.0
                                               target:self
                                             selector:@selector(doStuff)
                                             userInfo:nil
                                              repeats:YES];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号