Objective-C / Blocks - Isn't this a retain cycle?

回眸只為那壹抹淺笑 提交于 2019-12-08 09:30:45

问题


@interface ClassA : NSObject

@property (strong, nonatomic) dispatch_queue_t dispatchQ;
@property (strong, nonatomic) NSString *string;

@end

@implementation ClassA

- (id)init
{
    self = [super init];
    if (self) {
        _dispatchQ = dispatch_queue_create("com.classa.q", NULL);
    }

    return self;
}

- (void)longRunningTaskWithCompletion:(void(^)(void))completion
{
    dispatch_async(self.dispatchQ, ^{

        for (int i = 0; i < 10000; i++) {
            NSLog(@"%i", i);
        }

        dispatch_sync(dispatch_get_main_queue(), ^{
            self.string = @"Class A Rocks!";

            if(completion) {
                completion();
            }
        });
    });
}

@end

I'm thinking this code creates a retain cycle because the block in -longRunningTaskWithCompletion: captures self (to set the string property) in a block and adds the block to the dispatch queue property.


回答1:


There is a retain cycle, but it's temporary. The retain cycle looks like this:

  • self retains dispatchQ
  • dispatchQ retains the block
  • the block retains self

When the block returns, dispatchQ releases it. At that point, the retain cycle is broken. The block is deallocated and releases self.




回答2:


This is not a retain cycle. To have a retain cycle, self would need to retain the block while the block retains self. In the posted code, self does not retain the block. Therefore there is no retain cycle.



来源:https://stackoverflow.com/questions/15515093/objective-c-blocks-isnt-this-a-retain-cycle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!