使用block时如何避免循环引用

RT

- (void)dealloc
{
 
    NSLog(@"no cycle retain");
}
 
- (id)init
{
    self = [super init];
    if (self) {
 
#if TestCycleRetainCase1
 
        //会循环引用
        self.myblock = ^{
 
            [self doSomething];
        };
#elif TestCycleRetainCase2
 
        //会循环引用
        __block TestCycleRetain *weakSelf = self;
        self.myblock = ^{
 
            [weakSelf doSomething];
        };
 
#elif TestCycleRetainCase3
 
        //不会循环引用
        __weak TestCycleRetain *weakSelf = self;
        self.myblock = ^{
 
            [weakSelf doSomething];
        };
 
#elif TestCycleRetainCase4
 
        //不会循环引用
        __unsafe_unretained TestCycleRetain *weakSelf = self;
        self.myblock = ^{
 
            [weakSelf doSomething];
        };
 
#endif
 
        NSLog(@"myblock is %@", self.myblock);
 
    }
    return self;
}
 
- (void)doSomething
{
    NSLog(@"do Something");
}
 
int main(int argc, char *argv[]) {
    @autoreleasepool {
        TestCycleRetain* obj = [[TestCycleRetain alloc] init];
        obj = nil;
        return 0;
    }
}
经过上面的测试发现,在加了__weak和__unsafe_unretained的变量引入后,TestCycleRetain方法可以正常执行dealloc方法,而不转换和用__block转换的变量都会引起循环引用。
因此防止循环引用的方法如下:
__unsafe_unretained TestCycleRetain *weakSelf = self;

你可能感兴趣的:(ios,循环引用,block)