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

First of all, I am looking for a way to create nstimer scheduleTimerWithTimeInterval, which is repeated every 3 seconds 10 times, and then invalidates in the same way as without repeating the timer. Is it possible? Ideally, the extra selector lights up as soon as the timer is also invalid.

+7
objective-c
source share
1 answer

Just keep track of the number of cycles and keep a reference to the timer object. Then just invalidate it when you have 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]; } 
+9
source share

All Articles