block在日常开发中非常的常用,并且也十分的简单,但是在block内使用self也会引起循环引用的情况。
void(^myblock)() = ^() {
[self addSubView1];
};
myblock();
一般的解决方法是使用__weak来中断循环引用
__weak __typeof__(self) weakSelf = self;
void(^myblock)() = ^() {
[weakSelf addSubView1];
[weakSelf addSubView2];
};
myblock();
BUT,当self被释放后,也有可能导致weakSelf释放,比如上面的情况中[weakSelf addSubView2]中的weakSelf就有可能被释放,所以还需要
__strong __typeof(self) strongSelf = weakSelf;
来确保后面的weakSelf不被释放,此外在block内涉及使用weakSelf传值的情况也需要注意weakSelf被释放的可能,
__weak __typeof__(self) weakSelf = self;
void(^myblock)() = ^() {
__strong __typeof(self) strongSelf = weakSelf;
[strongSelf addSubView1];
[strongSelf addSubView2];
};
myblock();
总的来说block内涉及到多次使用weakSelf或者类似于通知传值的情况就需要使用strongSelf
这里推荐一个 YYKit 作者关于weakSelf和strongSelf的宏定义写法,使用时
@weakify(self);
@strongify(self);
if (!self) return;
宏定义如下
//--------------------weakSelf和strongSelf------------
#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
//--------------------end-------------------------
网友评论