在swift中,使用strongSelf的正确方式是什么?

9 浏览
0 Comments

在swift中,使用strongSelf的正确方式是什么?

在Objective-C中,在复杂的闭包中,我注意到使用weakSelf/strongSelf。

在Swift中使用strongSelf的正确方法是什么?

if let strongSelf = self {
  strongSelf.doSomething()
}

因此,在闭包中包含self的每一行都应该添加strongSelf检查吗?

if let strongSelf = self {
  strongSelf.doSomething1()
}
if let strongSelf = self {
  strongSelf.doSomething2()
}

有没有更优雅的方法来实现上述操作?

admin 更改状态以发布 2023年5月24日
0
0 Comments
0
0 Comments

使用strongSelf是一种检查self不等于nil的方法。当你有一个未来可能被调用的闭包时,重要的是传递一个weak实例的self,以避免通过持有对已去初始化的对象的引用创建保持周期。

{[weak self] () -> void in 
      if let strongSelf = self {
         strongSelf.doSomething1()
      }
}

本质上,你是在说如果self不存在,就不要持有对它的引用,也不要在它上执行操作。

0