gpt4 book ai didi

objective-c - 在 Objective C block 中隐藏 `self` 的成语?

转载 作者:太空狗 更新时间:2023-10-30 03:45:30 25 4
gpt4 key购买 nike

当我有一个 Objective C 实例创建一个需要引用该实例的 block 时,我经常通过一个弱指针这样做,该指针不会使该实例保持事件状态并产生一个保留周期,如下所示:

__weak MyType *const weakSelf = self;
void (^aBlock)() = ^(){
// Do things with weakSelf instead of self.
}

我想要一个成语来阻止我在 block 中使用强大的 self 。理想情况下,在使用惯用语时,如果我尝试在 block 中使用 self 而不是 weakSelf,则会出现编译错误。运行时错误也可以。

最佳答案

我有一个我不是特别喜欢的解决方案,但它可能会引发更好的答案。我将不回答这个问题,希望有更好的解决方案到来。

这是一种方法:

// 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();
}
}

我不相信这是值得的。有编译器警告可能就足够了,它们可能会变成错误?

关于objective-c - 在 Objective C block 中隐藏 `self` 的成语?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22511579/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com