block3

Block循环引用

typedef void (^blk_t)(void);

@interface JAXObject : NSObject {
    blk_t blk_;
}

@end

@implementation JAXObject

- (instancetype)init {
    if (self = [super init]) {

        blk_ = ^{
            NSLog(@"self = %@", self);
        };
        
    }
    return self;
}

- (void)dealloc {
    NSLog(@"dealloc");
}

@end

int main(int argc, const char * argv[]) {
    
    JAXObject *o = [[JAXObject alloc] init];
    NSLog(@"%@", o);
    
    return 0;
}

没有调用dealloc
o 持有blk_
blk_持有o, __weak避免循环引用

@implementation JAXObject

- (instancetype)init {
    if (self = [super init]) {
        
        __weak JAXObject *weakSelf = self;
        blk_ = ^{
            NSLog(@"self = %@", weakSelf);
        };
        
    }
    return self;
}

- (void)dealloc {
    NSLog(@"dealloc");
}

@end

也可以用__Block 解除循环,但必须要调用block。

@implementation JAXObject

- (instancetype)init {
    if (self = [super init]) {
        
        __block JAXObject *blockSelf = self;
        blk_ = ^{
            NSLog(@"self = %@", blockSelf);
            blockSelf = nil;
        };
        
    }
    return self;
}

- (void)dealloc {
    NSLog(@"dealloc");
}

- (void)exexblock {
    blk_();
}

@end

int main(int argc, const char * argv[]) {
    
    JAXObject *o = [[JAXObject alloc] init];
    [o exexblock];
    
    return 0;
}

执行dealloc调用

你可能感兴趣的:(block3)