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

What is the correct way of use strongSelf in swift?

在 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()
}

有没有办法让上面的更优雅?

如果您在闭包中使用 self,它会自动用作 strong。

如果您想避免保留循环,也可以使用 as weakunowned。它是通过在闭包参数之前传递 [unowned self] 或 [weak self] 来实现的。

使用 strongSelf 是一种检查 self 不等于 nil 的方法。当你有一个可能在将来某个时候调用的闭包时,传递一个 weak self 实例很重要,这样你就不会通过持有对已取消初始化的对象的引用来创建保留周期。

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

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

如果 self 不为零,您对 strongSelf 的使用似乎只针对调用 doSomethingN() 方法。相反,使用可选方法调用作为首选方法:

self?.doSomethingN()

另一种使用 weak self 而不使用 strongSelf

的方法
{[weak self] () -> void in 
      guard let `self` = self else { return }
      self.doSomething()
}

Swift 4.2

guard let self = self else { return }

参考:https://benscheirman.com/2018/09/capturing-self-with-swift-4-2/
参考文献 2:https://www.raywenderlich.com/5370-grand-central-dispatch-tutorial-for-swift-4-part-1-2