weakSelf在Block中被引用,因其是弱引用的关系存在被释放的风险。
在block中调用self会引起循环引用,但是在block中需要对weakSelf进行strong,保证代码在执行到block中,self不会被释放,当block执行完后,会自动释放该strongSelf
__weak typeof(self)_self= self; 外部weak
__strong typeof(_self) self =_self; 内部strong
强弱引用转换,用于解决代码块(block)与强引用self之间的循环引用问题
调用方式: @weakify_self
实现弱引用转换,@strongify_self
实现强引用转换
YYCategories 里的 YYCategoriesMacro.h
/**
Synthsize a weak or strong reference.
Example:
@weakify(self)
[self doSomething^{
@strongify(self)
if (!self) return;
...
}];
*/
#ifndef weakify
#if DEBUG
#if __has_feature(objc_arc)
#define weakify(object) autoreleasepool{} __weak __typeof__(object) weak##_##object = object;
#else
#define weakify(object) autoreleasepool{} __block __typeof__(object) block##_##object = object;
#endif
#else
#if __has_feature(objc_arc)
#define weakify(object) try{} @finally{} {} __weak __typeof__(object) weak##_##object = object;
#else
#define weakify(object) try{} @finally{} {} __block __typeof__(object) block##_##object = object;
#endif
#endif
#endif
#ifndef strongify
#if DEBUG
#if __has_feature(objc_arc)
#define strongify(object) autoreleasepool{} __typeof__(object) object = weak##_##object;
#else
#define strongify(object) autoreleasepool{} __typeof__(object) object = block##_##object;
#endif
#else
#if __has_feature(objc_arc)
#define strongify(object) try{} @finally{} __typeof__(object) object = weak##_##object;
#else
#define strongify(object) try{} @finally{} __typeof__(object) object = block##_##object;
#endif
#endif
#endif
用的时候就
@weakify(self)
dispatch_group_async(_operationsGroup, _operationsQueue, ^
{
@strongify(self)
if(self){
//安全生产,放心使用
}
} );
这两个宏一定成对出现,先@weakify再@strongify.可以很好的管理Block内部对self的引用