目标:block执行过程中,self不会释放;执行完可以释放。

最初

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

self.myBlock = ^() {    [self doSomething];};

或者使用了对象的属性

self.myBlock = ^() {    NSString *str = _str;    NSString *str2 = self.str;};

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

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

加入weak self

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

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

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

但是,如果是这样呢?

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

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

加入strong self

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

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