在苹果例如ARC的所有权与强,弱引用
MyViewController *myController = [[MyViewController alloc] init…];
MyViewController * __weak weakMyController = myController;
myController.completionHandler = ^(NSInteger result) {
MyViewController *strongMyController = weakMyController;
if (strongMyController) {
[strongMyController dismissViewControllerAnimated:YES completion:nil];
}
else {
// Probably nothing...
}
};
这到底是怎么回事?我很困惑: MyViewController * strongMyController = weakMyController;
这是否意味着weakMyController对它有强烈的引用,所以它会像weakMyController的保留计数+1一样?当您创建一个弱的iVar的强引用时会发生什么?
谢谢,但你能解释为什么这样做不会导致保留周期?这似乎是因为strongMyController会导致保留周期,因为strongMyController现在是指向myController的weakMyController的所有者。 – SukyaMaki
因为weakMyController不会以任何方式增加保留计数。弱代表不会创建保留周期的原因也是一样的。 – MikeS
好问题!如果在块中的任何位置使用现有的强引用myController的行,就会发生保留周期。是的,你确实在块中创建了一个新的强引用,但只有在块被执行时才会创建,并且到那时myController可能会停止存在,并且'strongMyController'将会为零。所以,这里没有保留周期。 – Macondo2Seattle