Ios 使用圆弧和块时保留循环
根据我的理解,当对象方法接收一个块作为完成参数时,我可以在块中发送“self”:Ios 使用圆弧和块时保留循环,ios,objective-c,automatic-ref-counting,objective-c-blocks,retain-cycle,Ios,Objective C,Automatic Ref Counting,Objective C Blocks,Retain Cycle,根据我的理解,当对象方法接收一个块作为完成参数时,我可以在块中发送“self”: [object doMethodWithCompletion:^{ [self doSomethingWhenThisMethodCompletes] }]; 但如果该对象“保留”了该块(保存以备将来使用),我应该发送一份我自己的“弱”副本: __weak __typeof__(self) weakSelf = self; object.savedBlock = ^{ [weakSelf doSometh
[object doMethodWithCompletion:^{
[self doSomethingWhenThisMethodCompletes]
}];
但如果该对象“保留”了该块(保存以备将来使用),我应该发送一份我自己的“弱”副本:
__weak __typeof__(self) weakSelf = self;
object.savedBlock = ^{
[weakSelf doSomethingWhenThisBlockIsCalledFromWithinObject];
};
但我也看到了一些变体,如:
__weak __typeof__(self) weakSelf = self;
object.savedBlock = ^{
__typeof__(weakSelf) strongSelf = weakSelf;
[strongSelf doSomethingWhenThisBlockIsCalledFromWithinObject];
};
我不清楚为什么/何时执行最后一个变量,在块内创建强引用可以确保如果块运行,对象不会在块中途释放,这可能导致意外的、难以调试的行为
typeof(self) weakSelf = self;
[anObject retainThisBlock:^{
[weakSelf foo];
// another thread could release the object pointed to by weakSelf
[weakSelf bar];
}];
现在[weakSelf foo]
会运行,但[weakSelf bar]
不会运行,因为weakSelf现在是零。如果在块内创建强引用,则在块返回之前无法释放对象