Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 使用圆弧和块时保留循环_Ios_Objective C_Automatic Ref Counting_Objective C Blocks_Retain Cycle - Fatal编程技术网

Ios 使用圆弧和块时保留循环

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

根据我的理解,当对象方法接收一个块作为完成参数时,我可以在块中发送“self”:

[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现在是
零。如果在块内创建强引用,则在块返回之前无法释放对象