Block will be retained by an object strongly retained by the captured object

防止iOS中私有属性在block中的循环引用

对于一般的@property修饰的属性我们可以使用__weak转换一下self来修饰

__weak typeof(self) weakSelf = self;
//然后把self.xxx变成weakself.xxx

那么.对于一些没有使用@property修饰的私有属性呢.比如一下这种.

@interface xxx () {
NSString *yyy;
}
// MARK: 1
//Block implicitly retains 'self'; explicitly mention 'self' to indicate this is intended behavior
//Insert 'self->'
self.button.didSelectBlock = ^{
yyy = @"123131133";
NSLog(@"%@",yyy);
};

编译器让我们使用self->去修饰这个属性,

当我们换成self->的时候

// MARK: 2
//Block will be retained by an object strongly retained by the captured object
self.button.didSelectBlock = ^{
self->yyy = @"12313123";
NSLog(@"%@",self->yyy);
};

循环引用了.那么我们如果把self替换成weakSelf呢

// MARK: 3
// ERROR
//Dereferencing a __weak pointer is not allowed due to possible null value caused by race condition, assign it to strong variable first
__weak typeof(self) weakSelf = self;
self.button.didSelectBlock = ^{
weakSelf->yyy = @"12313123";
NSLog(@"%@",weakSelf->yyy);
};
// MARK: 4
__weak typeof(self) weakSelf = self;
self.button.didSelectBlock = ^{
__strong typeof(weakSelf) strongSelf = weakSelf;
strongSelf->yyy = @"12313123";
NSLog(@"%@",strongSelf->yyy);
};