Referencing an NSOperation object in its own completion block with ARC

前端 未结 3 1296
醉梦人生
醉梦人生 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;
        });
    
    }];
    

提交回复
热议问题