当方法重新运行时,在方法中使用dispatch_after循环会导致多个同时发送

我正在创build一个简单的游戏。

我有以下代码:

- (void)doStuff { double delayInSeconds = [NSNumber randomFloatBetweenLowerBound:0.8f upperBound:2.6f]; // Own category on NSNumber returns random float. dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ // // Do stuff // if ([self shouldDoMoreStuff]) { [self doStuff]; } }); } 

这个方法是在viewDidLoad运行的,但是也会在玩家死亡的时候运行(按'Try Again'后)。

经过几次死亡,最终有许多迭代的方法同时运行,而不仅仅是一个。

我不太了解GCD和NSOperation等,但是我敢肯定我应该使用一些东西来控制这个 – 也许NSOperation – 所以在viewDidLoad中运行,然后当玩家死亡时,我取消操作,然后重新启动它。

正如我所说,我不太了解NSOperation所以我不知道它是否是:a)我应该使用什么和b)我应该如何使用它。

任何人都可以提供一些想法如何实现这一目标?

一如既往的感谢。

我修改了代码,以便您不需要删除和添加块等。

在你的viewController的.h文件中添加

 @property NSInteger currentCount; 

并且为了您的理解和演示,让我们假设我们在viewControllers视图发生触摸时重试它。

在.m文件中

 - (void)viewDidLoad { [super viewDidLoad]; _currentCount=0; [self doStuff:_currentCount]; } -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ //player dead, now start it again _currentCount++; [self doStuff:_currentCount]; } - (void)doStuff:(NSInteger)count { NSLog(@"came top %d",count); double delayInSeconds = 2; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ if(count==self.currentCount){ // // Do stuff // if([self shouldDoMoreStuff]) { [self doStuff:count]; } } }); } -(BOOL)shouldDoMoreStuff{ return YES; } 

既然你是在一个线程上完成这个工作(主队列在主线程上),一个简单的标志就足够了。 排队前检查它; 如果它closures,设置它并排队,否则跳过排队。 该块应该做的最后一件事是关掉国旗。

如果涉及多个线程,则需要一些专门用于线程间标记的devise,如调度信号量,以指示Block已经入队。