ios - 如何在init函数中实例化一个依赖self的对象?

标签 ios swift macos swift3 core-bluetooth

我知道在调用 super.init() 之前需要定义所有属性。但是如果一个属性的初始化依赖于 self 呢?在我的例子中,我需要初始化一个具有委托(delegate)的对象,我需要将其设置为 self。执行此操作的最佳方法是什么?

class MyClass : NSObject {
  var centralManager : CBCentralManager
  override init() {
    super.init()
    centralManager = CBCentralManager(delegate: self, queue: nil)
  }
}

这是错误的,因为centralManager没有在super.init之前初始化。但我也无法更改顺序,因为那样的话我将在 super.init 之前使用 self

最佳答案

问题

假设 CBCentralManager 定义如下

protocol CBCentralManagerDelegate { }

class CBCentralManager {
    init(delegate: CBCentralManagerDelegate, queue: Any?) {
    }
}

解决方案

这就是你应该如何定义你的类

class MyClass: CBCentralManagerDelegate {
    lazy var centralManager: CBCentralManager = {
        [unowned self] in CBCentralManager(delegate: self, queue: nil)
        }()
}

它是如何工作的?

如您所见,我正在使用 lazy 属性来填充 centralManager 属性。

lazy 属性有一个关联的闭包,该闭包在第一次读取 lazy 属性时执行。

由于只有在当前对象初始化后才能读取惰性属性,所以一切正常。

Where's NSObject?

As you can see I removed the inheritance of MyClass from NSObject. Unless you have a very good reason to inherit from NSObject well... don't do it :)

关于ios - 如何在init函数中实例化一个依赖self的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40074005/

相关文章:

ios - 使用图形 API 将图像发布到 Facebook 时始终获得 "(#324) Requires upload file"

swift - 具有由初始值设定项决定的泛型类型的不安全可变指针参数的类

ios - 在通知横幅中显示之前处理推送通知

macos - 查找具有(损坏的) future 日期的所有文件并修改为今天

xcode - Sierra 上 xcode-select 的仅终端安装错误

iphone - 如何从 iPhone 中的字符串设置 UIImageView 值?

ios - didUpdateToLocation 调用了两次,好的。为什么oldLocation两次都是nil?

objective-c - CFNotificationCenter 用法示例?

ios - 当玩家 "Remove"一场比赛正在进行时如何从 GKTurnBasedMatchmakerViewController 获得通知

ios - 什么是快速错误断点?如何使用它 ?所有异常错误都包含快速错误吗?