Ios 使用局部变量名是否正确;“自我”;在街区里?

Ios 使用局部变量名是否正确;“自我”;在街区里?,ios,objective-c-blocks,self,Ios,Objective C Blocks,Self,我发现这种结构(self)self=weakSelf 它允许remove-NSAssert宏self捕获,但我怀疑这样使用它是否正确 __weak typeof(self)weakSelf = self; self.signupBlock = ^{ __strong typeof(self)self = weakSelf; NSLog (@"%d", self.property) NSAssert((self.property > 5), @"Some messag

我发现这种结构(self)self=weakSelf

它允许remove-NSAssert宏self捕获,但我怀疑这样使用它是否正确

__weak typeof(self)weakSelf = self;
self.signupBlock = ^{
    __strong typeof(self)self = weakSelf;
    NSLog (@"%d", self.property)
    NSAssert((self.property > 5), @"Some message");
}
请指教

对不起,我得先说使用 __strong typeof(self)strongSelf=weakSelf


当使用NSAssert宏时,构造结果会出现警告,我想会出现mem循环,因为它包含self

self
只是一个变量名,所以在本地重新定义它是完全正确的。它甚至可能更倾向于

__strong typeof(weakSelf) strongSelf = weakSelf;
因为

  • 它使代码易于阅读
  • 它可以防止您错误地引用“real”
    self
    ,并可能创建保留周期

此外,您可能希望查看关于何时在块中使用弱/strong
self
的答案,以及用于整洁的
@weakify
/
@strongify
宏的库。将代码更改为,以便清楚地表明您在块中只引用了
strongSelf

__weak typeof(self) weakSelf = self;
self.signupBlock = ^{
    typeof(weakSelf) strongSelf = weakSelf;
    if strongSelf {
        NSLog (@"%d", strongSelf.property)
        NSAssert((strongSelf.property > 5), @"Some message");
    }
}

您的代码设置了到self
\uuuu弱类型(self)weakSelf=self的弱连接。然后,当以后需要调用self时,它会建立到self
typeof(weakSelf)strongSelf=weakSelf的强连接
并检查self是否仍然存在(尚未释放)
如果是strongSelf{
。如果是,则在运行其余代码时,强连接将使其保持活动状态,这在许多情况下可能涉及另一个块来调用主线程(即,因此强连接).

是的,在ObjC中使用
self
作为变量名是可以的

对于需要中断由存储块引起的保留周期的情况,我制作了一个奇特的宏:

#define StrongSelf  __strong  __typeof__((__typeof__(self))self)
#define WeakSelf    __weak    __typeof__((__typeof__(self))self)

#define RecoverSelf  for (BOOL _continue_loop = YES; _continue_loop; _continue_loop = NO)              \
                     for (StrongSelf this = self; this != nil && _continue_loop; _continue_loop = NO)  \
                     for (StrongSelf self = this; _continue_loop; _continue_loop = NO)
#define WeakenSelf   for (BOOL _continue_loop = YES; _continue_loop; _continue_loop = NO) \
                     for (WeakSelf   this = self;  _continue_loop; _continue_loop = NO)   \
                     for (WeakSelf   self = this;  _continue_loop; _continue_loop = NO)
您可以这样使用:

WeakenSelf {
    _signupBlock = ^{
        RecoverSelf {
            NSLog (@"%d", self.property)
            NSAssert((self.property > 5), @"Some message");
        }
    }
}

NSAssert
只应在Objective-C方法中使用,因此它使用
self
\u cmd
。块不是Objective-C方法,因此您不应在其中使用
NSAssert
。您可能应该使用
NSAssert

仅使用
self
有什么问题吗eakSelf
for?因为OP在块中编写代码,这限制了直接访问块中的自我对象。不,它根本不知道。不清楚如何使用它,但看起来很好在
弱块中引用
自我
的每个引用都很弱(就像你的
\u弱类型的…
)。因此,对
self
的弱引用将传递到阻止保留循环的块。-
RecoverSelf做相反的事情,对
self
内部的引用将再次变强。此外,只有
self
仍在内存中并且没有变为
nil
时,代码才会执行——因此基本上是这样与您在初始示例中所做的相同,只是使用了更好的语法。通常这样做,但没有检查。很好的练习,谢谢。在Subject问题中,变量名self很感兴趣。是的,但使用NSAssert looks会遇到问题。我对局部变量的“self”命名感兴趣,并且担心一些问题。现在我对局部使用“self”很平静.