如何使用 ARC 手动保留在 Swift 中?

How do I manually retain in Swift with ARC?

我在 iOS 应用程序中使用带有 ARC 的 Swift 3,我想手动保留一个对象。

我试过 object.retain() 但 Xcode 说它在 ARC 模式下不可用。有没有其他方法可以做到这一点,告诉 Xcode 我知道我在做什么?


长版:

我有一个 LocationTracker class 将自己注册为 CLLocationManager 的委托。当用户的位置发生变化时,它会更新一个名为 location 的静态变量。我的代码中需要位置的其他部分访问此静态变量,而无需或不需要对 LocationTracker 实例的引用。

此设计的问题是未保留委托,因此在 CLLocationManager 向其发送消息时会释放 LocationTracker,从而导致崩溃。

我想在将 LocationTracker 设置为委托之前手动增加其引用计数。该对象永远不会被释放,因为只要应用程序处于 运行.

状态,就应该监视该位置

我找到了一个解决方法,即使用一个静态变量 'instance' 来保留对 LocationTracker 的引用。我认为这种设计不够优雅,因为我永远不会使用 'instance' 变量。我可以摆脱它并显式增加引用计数吗?

正如所声称的那样,这个问题不是重复的,因为 other question 是关于 Objective-C,而这个问题是关于 Swift。

这可以通过 withExtendedLifetime(_:_:) 函数轻松完成。来自文档:

Evaluates a closure while ensuring that the given instance is not destroyed before the closure returns.

干杯!

原来解决方案是重新启用retain()和release():

extension NSObjectProtocol {
  /// Same as retain(), which the compiler no longer lets us call:
  @discardableResult
  func retainMe() -> Self {
    _ = Unmanaged.passRetained(self)
    return self
  }

  /// Same as autorelease(), which the compiler no longer lets us call.
  ///
  /// This function does an autorelease() rather than release() to give you more flexibility.
  @discardableResult
  func releaseMe() -> Self {
    _ = Unmanaged.passUnretained(self).autorelease()
    return self
  }
}