YYCategories中@weakify 和 @strongify

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;

        ...

    }];

*/#ifndefweakify#ifDEBUG#if__has_feature(objc_arc)#defineweakify(object) autoreleasepool{} __weak __typeof__(object) weak##_##object = object;#else#defineweakify(object) autoreleasepool{} __block __typeof__(object) block##_##object = object;#endif#else#if__has_feature(objc_arc)#defineweakify(object) try{} @finally{} {} __weak __typeof__(object) weak##_##object = object;#else#defineweakify(object) try{} @finally{} {} __block __typeof__(object) block##_##object = object;#endif#endif#endif#ifndefstrongify#ifDEBUG#if__has_feature(objc_arc)#definestrongify(object) autoreleasepool{} __typeof__(object) object = weak##_##object;#else#definestrongify(object) autoreleasepool{} __typeof__(object) object = block##_##object;#endif#else#if__has_feature(objc_arc)#definestrongify(object) try{} @finally{} __typeof__(object) object = weak##_##object;#else#definestrongify(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的引用

链接:https://www.jianshu.com/p/021680aba82a 出处

你可能感兴趣的:(YYCategories中@weakify 和 @strongify)