Referencing an NSOperation object in its own completion block with ARC

前端 未结 3 1301
醉梦人生
醉梦人生 2021-02-05 18:46

I\'m having difficulty converting some NSOperation code to ARC. My operation object uses a completion block, which in turn contains a GCD block that updates the UI on the main t

相关标签:
3条回答
  • 2021-02-05 18:51

    I'm not certain about this, but the correct way to do it is possibly to add __block to the variable in question, and then set it to nil at the end of the block to ensure that it is released. See this question.

    Your new code would look like this:

    NSOperationSubclass *operation = [[NSOperationSubclass alloc] init];
    __block NSOperationSubclass *weakOperation = operation;
    
    [operation setCompletionBlock:^{
        dispatch_async( dispatch_get_main_queue(), ^{
    
            // fails the check
            NSAssert( weakOperation != nil, @"pointer is nil" );
    
            ...
            weakOperation = nil;
        });
    
    }];
    
    0 讨论(0)
  • 2021-02-05 18:54

    Accepted answer is correct. However there is no need to weakify operation as of iOS 8 / Mac OS 10.10:

    the quote from NSOperation documentation on @completionBlock:

    In iOS 8 and later and OS X v10.10 and later, this property is set to nil after the completion block begins executing.

    See also this tweet from Pete Steinberger.

    0 讨论(0)
  • 2021-02-05 19:06

    Another option would be:

    NSOperationSubclass *operation = [[NSOperationSubclass alloc] init];
    __weak NSOperationSubclass *weakOperation = operation;
    
    [operation setCompletionBlock:^{
        NSOperationSubclass *strongOperation = weakOperation;
    
        dispatch_async(dispatch_get_main_queue(), ^{
            assert(strongOperation != nil);
            ...
        });
    }];
    
    [operationQueue addOperation:operation];
    

    I assume you also add operation object to an NSOperationQueue. In that case, the queue is retaining an operation. It is probably also retaining it during execution of the completion block (although I haven't found official confirmation about the completion block).

    But inside you completion block another block is created. That block will be run at some point in time later, possibly after NSOperations's completion block is run to an end. When this happens, operation will be released by the queue and weakOperation will be nil. But if we create another strong reference to the same object from operation's completion block, we'll make sure operation will exist when the second block is run, and avoid retain cycle because we don't capture operation variable by the block.

    Apple provides this example in Transitioning to ARC Release Notes see the last code snippet in Use Lifetime Qualifiers to Avoid Strong Reference Cycles section.

    0 讨论(0)
提交回复
热议问题