block循环引用

2016-12-07  本文已影响9人  7dfa9c18c1d1

我们都知道,在使用block的时候需要特别注意循环使用问题,比如在一个ClassA中:

@interface DDDViewController ()

@property (nonatomic, copy) void(^block)();

@property (nonatomic, strong) NSString *dog;

@end

@implementation DDDViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.dog = @"222";

    self.block = ^(){
            NSLog(@"%@",self.dog);
    };
    
    self.block();
}

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

@property (nonatomic, copy) void(^block)();

@property (nonatomic, strong) NSString *dog;

@end

@implementation DDDViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.dog = @"222";
    
    __weak DDDViewController *weak = self;
    self.block = ^(){
        NSLog(@"====%@",weak.dog);
    };
    
    self.block();  
}

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

使用weak修饰即可打破刚才的闭环。但是,比如有个这样的情景:
当前这个DDDViewController是被ClassA给Push出来的,然后执行下面的代码:

@interface DDDViewController ()

@property (nonatomic, copy) void(^block)();

@property (nonatomic, strong) NSString *dog;

@end

@implementation DDDViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.dog = @"222";
    
    __weak DDDViewController *weak = self;
    self.block = ^(){
         dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"====%@",weak.dog);
        });
    };
    
    self.block();  
}

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

大家认为打印是什么结果?

2016-12-07 10:22:00.444 CeShi[1180:47515] dealloc
2016-12-07 10:22:03.491 CeShi[1180:47515] ====(null)
2016-12-07 10:22:12.285 CeShi[1180:47515] ====222
2016-12-07 10:22:14.161 CeShi[1180:47515] dealloc
@interface DDDViewController ()

@property (nonatomic, copy) void(^block)();

@property (nonatomic, strong) NSString *dog;

@end

@implementation DDDViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.dog = @"222";
    
    __weak DDDViewController *weak = self;
    self.block = ^(){
        __strong typeof(self) strongSelf = weak;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"====%@",strongSelf.dog);
        });
    };
    
    self.block();
}

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

所以我们平常写block的时候,并且需要在block中用到self的时候,可以采取这种方式

[UIView animateWithDuration:0.2 animations:^{
    self.alpha = 1;
}];
上一篇 下一篇

猜你喜欢

热点阅读