【发布时间】:2013-01-07 11:04:11
【问题描述】:
我想知道问题主题中的变量声明是否合法。想象一下下面的代码:
__weak typeof(self) weakSelf = self;
[self doSomethingThatMayCauseRetainCycleWithBlock:^{
typeof(self) self = weakSelf; // <---- !!!!
if (self == nil) return;
NSAssert(self.someProperty != nil, @"This doesn't lead to retain cycle!");
[self doSomething];
self.someProperty = someValue;
// even
self->someIvar = anotherValue;
}
此代码在 Xcode 4.5.2 中完美运行,仅发出警告 Declaration shadows a local variable。
这个怪癖有什么意义:
- 将
self重新声明为对弱变量的强引用后,您可以安全地在块内部/外部复制/移动代码,而不会冒偶尔创建保留循环的风险(除了 ivars,但它们是邪恶的)。 -
块中的
NSAssert不再导致保留循环。
更新
我发现这种技术在libextobjc 中用于@weakify/@strongify 宏。
【问题讨论】:
-
了解弱化和强化的好资源:holko.pl/2015/05/31/weakify-strongify
标签: objective-c automatic-ref-counting objective-c-blocks