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

Vad*_*ick 4 retain automatic-ref-counting swift swift3 swift3.0.2

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

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


长版:

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

这种设计的问题在于没有保留委托,因此在 CLLocationManager 向它发送消息时,LocationTracker 被释放,导致崩溃。

我想在将它设置为委托之前手动增加 LocationTracker 的引用计数。无论如何,该对象永远不会被释放,因为只要应用程序正在运行,就应该监视该位置。

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

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

Rud*_*vič 7

这很容易通过withExtendedLifetime(_:_:)函数完成。从文档:

评估闭包,同时确保给定的实例在闭包返回之前不会被销毁。

干杯!


Vad*_*ick 6

解决方案原来是重新启用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
  }
}
Run Code Online (Sandbox Code Playgroud)