block的循环引用

@interface Person : NSObject

@property (nonatomic, copy) void(^block)();//对象持有block

@property (nonatomic, assign) NSInteger age;

- (void)test;

@end

#import "Person.h"

@implementation Person

- (void)test{  
    self.block = ^(){
        NSLog(@"%ld",self.age);
    };
}

- (void)dealloc{
    NSLog(@"Preson dealloc");//如果对象被销毁,则打印dealloc信息
}

@end
#import "Person.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        Person *p = [[Person alloc] init];
        
        p.age = 15;
        
        [p test];
        
    }
    return 0;
}

打印结果:没有打印"Preson dealloc"

怎么办呢?把self用__weak修饰就解决了

- (void)test{
    
    __weak typeof(self) weakSelf = self;
    
    self.block = ^(){
        NSLog(@"%ld",weakSelf.age);
    };
}

打印结果:XX-XX-XX XX:XX:XX test[44752:1753437] Person dealloc

循环引用的触发条件

并不是只要在block中引用self就会产生循环引用,一定要同时满足这两个条件:

  • 如果接受block的一方,通过属性记录了block
  • 同时接收方不会主动释放(单例),才会出现循环引用

循环引用的解决方法

__weak typeof(self) weakSelf = self;

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