简体   繁体   中英

Create singleton instance via extension per app?

In the Apple documentation , it says that some instances need to be create once per app like 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.

Is doing something convenient like below safe or is there a better way?

public extension HKHealthStore {

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

        struct Singleton {
            static let instance = HKHealthStore()
        }

        return Singleton.instance
    }

}

That way I can do this without polluting with custom managers: HKHealthStore.shareInstance?.requestAuthorizationToShareTypes

Is this ok or is there a better architectural approach?

I would do it in this way:

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

Now you can use MyHealthStore.sharedInstance and it will always return the same store.

You can also achieve the same without any subclassing:

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

And now you can use MyCustomClass.sharedInstance.healthStore

A cleaner and faster way to have a singleton HKHealthStore instance in your app without subclassing it (which is discouraged by Apple) or creating a dummy class, would be via a simple extension:

extension HKHealthStore {
    static let shared = HKHealthStore()
}

This way you could simply..

HKHealthStore.shared.requestAuthorization(...)
HKHealthStore.shared.execute(query)

and that's it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM