stopping a programming loop
When my main viewController is first clicked, it starts showing a demo (on repeat) as follows:
showingDemo = YES;
[self startDemo];
- (void)startDemo {
if (showingDemo) {
[self performSelector:@selector(stepone) withObject:nil afterDelay:1.5f];
[self performSelector:@selector(steptwo) withObject:nil afterDelay:2.0f];
[self performSelector:@selector(stepthree) withObject:nil afterDelay:3.8f];
[self performSelector:@selector(stepfour) withObject:nil afterDelay:4.3f];
[self performSelector:@selector(startDemo) withObject:nil afterDelay:5.6f];
}
}
When it is clicked a second time, I bring a new ViewController to the screen
showingDemo = NO;
[self.view addSubview:newView];
I thought this would stop the endless loop.
When the user returns back to my main viewController:
开发者_如何学Go[newView.view removeFromSuperview];
And clicks on the screen again:
showingDemo = YES;
[self startDemo];
In testing my app, if I click back quickly (before the loop has had time to end, the program seems to be running through the loop twice - the one that was previously going and the new one - and therefore it looks all weird, with the 'stepthree' function happening before 'stepone' and so forth.
Anybody know a better way to STOP the loop I've programmed for good so that when I go to start it again later, it doesn't run multiple loops thinking that the previous one hasn't been finished?
Thanks so much!
When you set showingDemo to NO, call NSObject's cancelPreviousPerformRequestsWithTarget:
to cancel any pending perform requests:
showingDemo = NO;
[NSObject cancelPreviousPerformRequestsWithTarget:self];
[self.view addSubview:newView];
精彩评论