【发布时间】:2013-09-08 09:58:43
【问题描述】:
我是一个出生的 Obj-C 程序员,只生活在后 ARC 世界。不过,为了我自己的效率,我最近决定通过 Apple 的 Transitioning to ARC Release Notes。在 ARC Introduces New Lifetime Qualifiers 部分中,有一个标题为使用生命周期限定符来避免强引用循环 的小节,它描述了潜在地使用限定符以避免潜在的保留循环的各种方法.
我的问题与最后两个示例有关。最后两个示例中的第一个使用了我经常使用的模式,以避免过早地从非主线程中释放 UIKit 对象:
MyViewController *myController = [[MyViewController alloc] init…];
// ...
MyViewController * __weak weakMyViewController = myController;
myController.completionHandler = ^(NSInteger result) {
[weakMyViewController dismissViewControllerAnimated:YES completion:nil];
};
在上面的示例中,weakMyViewController 对象是使用对myController 的弱引用创建的,因此引用weakMyViewController 的块可以使用它,并且在返回块时,weakMyViewController 可以安全地退出范围而不减少被引用的底层 UIKit 对象的引用计数。
不过,在下一个示例中,Apple 显示了以下“非平凡循环”代码:
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...
}
};
在上面提供的“非平凡”示例中,相同的 __weak 限定符用于从块内引用 UIKit 对象,但随后代码创建了对同一对象的本地隐式 __strong 引用。然后对本地__strong 引用进行非零条件测试,然后对其进行操作。
我的两个问题是:
Obj-C 程序员在实现第二种设计模式(与前者相反)时应该考虑什么?我不明白苹果关于“非平凡循环”的评论
__strong对weakMyController的引用如何不增加原始myController对象的保留计数?如果weakMyController只是指向myController指向的底层对象的指针,那么强指针(即stringMyController)不会增加底层对象的保留计数(myController指向的对象) ?
【问题讨论】:
标签: ios objective-c c macos automatic-ref-counting