对此我有一个我不是特别喜欢的解决方案,但它可能会引发更好的答案。我不会回答这个问题,希望能有更好的解决方案。
这是一种方法:
// Here's a method definition…
-(void) aMethod
{
// Want to create a block in which its impossible to refer to strong "self".
// Begin a new scope to do this in.
{
// Within this scope, cover the existing "self" with a weak variant.
__weak STWeatherTableViewController const *weakSelf = self;
__weak STWeatherTableViewController const *self = weakSelf;
// Sadly it's _not_ possible to simply do:
// __weak STWeatherTableViewController const *self = self;
// … it gives a warning about initialisation of a variable form its own
// uninitialised value, which makes sense, though you might hope the
// compiler would work out what's going on.
// Make a block that captures the covered self and does something with it.
void (^exampleBlock)() = ^(){ [self lineHeight]; };
exampleBlock();
}
// Now, back in the scope of the original method, "self" is non weak
// again.
[self doSomething];
}
我想,如果你真的很关心这个,你可以使用宏。它至少会抽象出这个想法,并使代码中的用途很容易找到和注意:
#define WEAKEN_SELF(classType) \
__weak classType const *weakSelf = self; \
__weak classType const *self = weakSelf
甚至:
#define WEAKEN_SELF(classType) \
__weak classType const *weakSelfTemporary##__LINE__ = self; __weak classType const *self = weakSelfTemporary##__LINE__;
你会这样使用它:
-(void) testMethod
{
// You still need that scope or you cover the original "self".
{
WEAKEN_SELF(STWeatherTableViewController)
void (^exampleBlock)() = ^(){ [self someMethodOrOther]; };
exampleBlock();
}
}
我不相信这是值得的努力。有编译器警告可能就足够了,它们可能会变成错误?