Objective-C, cancel a dispatch queue using UI event

后端 未结 3 2138
盖世英雄少女心
盖世英雄少女心 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:13

    If you declare your BOOL using __block, then it can be changed outside of the block execution, and the block will see the new value. See the documentation for more details.

    An example:

    @interface SNViewController ()
    {
        BOOL*   cancelledPtr;
    }
    
    @end
    
    @implementation SNViewController
    
    - (IBAction)start:(id)sender
    {
        __block BOOL cancelled = NO;
    
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            while (!cancelled) {
                NSLog(@"running");
                sleep(1);
            }        
            NSLog(@"stopped");
        });
    
        cancelledPtr = &cancelled;
    }
    
    - (IBAction)stop:(id)sender
    {
        if (cancelledPtr)
        {
            NSLog(@"stopping");
    
            *cancelledPtr = YES;
        }
    }
    
    @end
    

    Alternatively, use an ivar in your class to store the BOOL. The block will implicitly make a copy of self and will access the ivar via that. No need for __block.

    @interface SNViewController ()
    {
        BOOL   cancelled;
    }
    
    @end
    
    @implementation SNViewController
    
    - (IBAction)start:(id)sender
    {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            while (!cancelled) {
                NSLog(@"running");
                sleep(1);
            }        
            NSLog(@"stopped");
        });
    }
    
    - (IBAction)stop:(id)sender
    {
        NSLog(@"stopping");
        cancelled = YES;
    }
    
    @end
    

提交回复
热议问题