块的保留周期是否适用于块调用的方法?

Does retain cycle for a block applies for methods the block call?

好的,我们知道如果我们这样做可能会有一个保留周期

[someObject messageWithBlock:^{ [self doSomething]; }];

解决方案是这样的

__weak typeof(self) weakSelf = self;
[someObject messageWithBlock:^{ [weakSelf doSomething]; }];

但是如果我们执行最后一个代码但是 doSomething 有很多对 self 的引用怎么办?喜欢:

- (void) doSomething {
    self.myProperty = @"abc";
    [self doOtherThing];
}

这会创建一个保留周期吗?

那这个呢:

__weak typeof(self) weakSelf = self;
[someObject messageWithBlock:^{ 
   self.onError(NSLocalizedStringFromTable(@"Error", MY_TABLE, nil))
}];

其中 MY_TABLE 是 #define?

当我们有超过 2 个对象引用时,会创建保留循环。当超出范围时,ARC 减少保留计数。但是如果我们对一个对象有超过 1 个强引用,那么就会发生循环引用。

(i) 要删除循环保留,始终采用对象的弱引用,特别是在块的情况下。因为块创建了一个单独的对象副本,我喜欢你所做的:

 __weak typeof(self) weakSelf = self; 
[someObject messageWithBlock:^{ 
[weakSelf doSomething];
 }]; 

(ii) 对于功能没有任何问题

- (void) doSomething {
    self.myProperty = @"abc";
    [self doOtherThing];
}   

此代码中没有保留循环:

__weak typeof(self) weakSelf = self;
[someObject messageWithBlock:^{ [weakSelf doSomething]; }];

- (void) doSomething {
    self.myProperty = @"abc";
    [self doOtherThing];
}

说明

在上面的代码中

[weakSelf doSomething];

表示接收者对象(self)现在变成了 weakSelf 即。 doSomething 中对 self 的任何调用都将引用 weakSelf。 因此在 doSomething 中引用 self 不会创建一个保留周期。

下面说说代码:

__weak typeof(self) weakSelf = self;
[someObject messageWithBlock:^{ 
   self.onError(NSLocalizedStringFromTable(@"Error", MY_TABLE, nil))
}];

因为块内的接收者对象是 self,而不是 weakSelf,这将创建一个保留周期。