CLKComplicationServer初始化已初始化的单例类CLKComplicationDataSource,尽管init()是私有的

时间:2017-08-03 12:43:13

标签: swift singleton watch-os-3 apple-watch-complication

要更新手表上的复杂功能,我使用单件类ComplicationController(以下省略了相关代码):

final class ComplicationController: NSObject, CLKComplicationDataSource {

    static let shared = ComplicationController() // Instantiate the singleton

    private override init() {
        super.init()
        print("====self: \(self): init")
    } // Others can't init the singleton
}

单例由扩展代表在手表上创建:

class ExtensionDelegate: NSObject, WKExtensionDelegate {

  override init() {
    super.init()
        _ = ComplicationController.shared           
  }
}

当我在上面的print语句中使用断点启动监视扩展时,执行中断并且堆栈跟踪为:
enter image description here

当我在一步中执行print语句时,调试器显示:

====self: <Watch_Extension.ComplicationController: 0x7bf35f20>: init  

当我继续时,执行在同一个断点处再次中断,堆栈跟踪为:
enter image description here

再过一步,调试器显示:

====self: <Watch_Extension.ComplicationController: 0x7d3211d0>: init  

显然,CLKComplicationServer已经创建了单例的另一个实例。

我的问题是:我有什么问题或者这是一个错误吗?如果是错误,是否有解决方法?

PS:在ComplicationController中初始化ExtensionDelegate无法帮助 。在这种情况下,只要在代码中的任何位置使用ComplicationController.shared,就会创建第二个实例。

1 个答案:

答案 0 :(得分:0)

我找到了解决方法:

不要在应用中实例化单例,即不要在任何地方使用ComplicationController.shared
如果您必须在ComplicationController.shared中拨打电话,请发送通知,例如:到默认通知中心 ComplicationController单身人士必须已注册此类通知,当收到通知时,必须执行所需的功能。
这对我有用。