Objective C中block的循环引用问题

目标:block执行过程当中,self不会释放;执行完能够释放。bash

最初

block中直接使用self会强引用。spa

self.myBlock = ^() {
    [self doSomething];
};
复制代码

或者使用了对象的属性code

self.myBlock = ^() {
    NSString *str = _str;
    NSString *str2 = self.str;
};
复制代码

在这样的状况下,self强引用block,block也持有该对象,致使循环引用。对象

要注意的是,只有在self强引用block的时候才会有这样的问题。通常使用GCD或NSOperation时使用的内联block是不会出现循环引用的。io

加入weak self

__weak __typeof(self) weakSelf = self;
self.myBlock = ^() {
    [weakSelf doSomething];
};
复制代码

这样,self持有了block,但block对self是弱引用,就不会致使循环引用了。class

而在[weakSelf doSomething]过程当中,self是不会释放的,完美。循环

可是,若是是这样呢?引用

__weak __typeof(self) weakSelf = self;
self.myBlock = ^() {
    [weakSelf doSomething];
    [weakSelf doSomething2];
};
复制代码

[weakSelf doSomething][weakSelf doSomething2]之间,self可能会被释放掉。这可能会致使奇怪的问题。word

加入strong self

__weak __typeof(self) weakSelf = self;
self.myBlock = ^() {
    __strong __typeof(self) strongSelf = weakSelf;
    [strongSelf doSomething];
    [strongSelf doSomething2];
};
复制代码

这样,block既没有持有self,又能保证block在执行过程当中self不被释放,真正达到了最初的目标。di

相关文章
相关标签/搜索