重新运行方法时,在方法中循环dispatch_after会导致许多同时分派 [英] Looping dispatch_after in a method causes many simultaneous dispatches when method is rerun

查看:208
本文介绍了重新运行方法时,在方法中循环dispatch_after会导致许多同时分派的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个简单的游戏.

I'm creating a simple game.

我有以下代码:

- (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中运行,但在玩家死亡时也将运行(按重试"后).

This method is run in viewDidLoad, but it is also run when the player dies (after pressing 'Try Again').

几次死亡之后,该方法最终会同时运行许多迭代,而不仅仅是一次.

After several deaths, eventually there are many iterations of this method being run simultaneously, rather than just one.

我对GCD和NSOperation等了解不多,但是我很确定我应该使用某些东西来控制它-也许NSOperation-所以在viewDidLoad中它可以运行,然后在播放机上运行死了,我取消了该操作,然后重新启动.

I don't know much about GCD and NSOperation etc, but I'm pretty sure I should be using something to control this - perhaps NSOperation - so in viewDidLoad it is run, then when the player dies, I cancel the operation, and restart it.

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

As I say, I don't know much about NSOperation so I don't know if it's: a) What I should be using and b) How I should be using it.

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

Can anyone provide some thoughts on how to achieve this?

一如既往的感谢.

推荐答案

我修改了代码,因此您无需删除和添加块等.

i modified the code so that you don't need block removal and adding etc.

在viewController的.h文件中添加

In .h file of your viewController add

@property NSInteger currentCount;

为便于您理解和演示,假设我们在viewControllers视图上发生触摸时尝试重试.

And for your understanding and demonstration, lets assume we retry it when a touch happens on viewControllers view.

在.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;
}

这篇关于重新运行方法时,在方法中循环dispatch_after会导致许多同时分派的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆