The sequence of sending a call in a method causes many simultaneous sendings when the method is called again

I am creating a simple game.

I have the following code:

- (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];
        }
    });
}

This method starts in viewDidLoad, but it also starts when the player dies (after clicking "Try Again").

After several deaths, in the end, many iterations of this method are performed simultaneously, and not just one.

I don’t know much about GCD, NSOperationetc., but I’m sure I should use something to control this - perhaps NSOperation- so viewDidLoadit starts up in it, and then when the player dies, I cancel the operation and restart it .

, NSOperation, , : a) ) .

- , ?

, .

+4
2

i , ..

.h viewController

@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;
}
-1

( ), . , ; , , enqueuing. , , - .

, -, , , , .

+1

Source: https://habr.com/ru/post/1526059/


All Articles