Objective-C, cancel a dispatch queue using UI event

后端 未结 3 2126
盖世英雄少女心
盖世英雄少女心 2020-12-08 16:51

Scenario:

  • User taps a button asking for some kind of modification on address book.
  • A method is called to start this modification and an alert view is
3条回答
  •  抹茶落季
    2020-12-08 17:25

    Try to apply the following code sample to your situation:

    __block UIView * tempView = [[UIView alloc] initWithFrame:CGRectMake(50, 100, 220, 30)];
    [tempView setBackgroundColor:[UIColor grayColor]];
    [self.view addSubview:tempView];
    [tempView release];
    
    __block BOOL cancel = NO;
    //点击之后就会开始执行这个方法
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        int i = 0;
        while (i < 1000000000 && cancel == NO) {
            i++;
        }
        NSLog(@"Task end: i = %d", i);
        //这个不会执行,因为在之前,gcd task已经结束
        [tempView removeFromSuperview];
    });
    
    //1s 之后执行这个方法
    double delayInSeconds = 1.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        NSLog(@"A GCD Task Start");
        cancel = YES;
        [tempView setBackgroundColor:[UIColor blackColor]];
    });
    

提交回复
热议问题