Search code examples
iosswiftswift2ios9

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?


Solution

  • 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