NSTimer仅重复x次,然后在无效时调用选择器

Tim*_*mbo 7 objective-c

主要是我正在寻找一种方法来创建一个nstimer scheduledTimerWithTimeInterval,它每3秒重复10次,然后就像无重复计时器一样无效.这可能吗?理想情况下,一旦定时器无效,另外的选择器将会触发

Ale*_*yne 9

只需跟踪循环次数并保持对计时器对象的引用.然后在你做得足够的时候让它失效.

// 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];
}
Run Code Online (Sandbox Code Playgroud)