通过每个应用程序的扩展创建单例实例?

Create singleton instance via extension per app?

Apple documentation 中,它表示某些实例需要为每个应用程序创建一次,例如 HKHealthStore:

You need only a single HealthKit store per app. These are long-lived objects. Create the store once, and keep a reference for later use.

像下面这样方便安全还是有更好的方法?

public extension HKHealthStore {

    class var sharedInstance: HKHealthStore? {
        if !HKHealthStore.isHealthDataAvailable() {
            return nil
        }

        struct Singleton {
            static let instance = HKHealthStore()
        }

        return Singleton.instance
    }

}

这样我就可以在不影响自定义管理器的情况下执行此操作: HKHealthStore.shareInstance?.requestAuthorizationToShareTypes

这样可以吗还是有更好的架构方法?

我会这样做:

class MyHealthStore:HKHealthStore {
    static let sharedInstance = MyHealthStore()
}

现在您可以使用 MyHealthStore.sharedInstance,它将始终 return 同一家商店。

你也可以在没有任何子类化的情况下实现同样的效果:

class MyCustomClass:NSObject {
    static let sharedInstance = MyCustomClass()
    let healthStore = HKHealthStore()
}

现在您可以使用 MyCustomClass.sharedInstance.healthStore