I realize singleton's aren't aways preferred, however per Apple docs while using HealthKit "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 there any drawback to using a singleton here in order to persist 1 single HKHealthStore per app session (as opposed to either instantiating multiple HKHealthStores in different classes, or attempting to pass around the same instance)?
Secondly, would it be preferred to have a separate Singleton class for both the iPhone app and the Watch Extension? Or could both use a single Singleton class?
import Foundation
import HealthKit
class HealthStoreSingleton {
class var sharedInstance: HealthStoreSingleton {
struct Singleton {
static let instance = HealthStoreSingleton()
}
return Singleton.instance
}
let healthStore = HKHealthStore()
}
I found that if you are using anchored update queries, then you should realise that your HealthStore is blocked until your updateHandler function returns. So you cannot use the HealthStore singleton from your updateHandler.
You can solve this by either using concurreny: queue operations on an operation queue, and return from your updateHandler before starting to process the operations.
Or you can create a second HealthStore instance, and use that from inside the updateHandler. I must say that I did some experiments to know that it works, but that I did not use this scheme in a real-life situation. So I don't know the performance impact.
Regarding your second question: the app and the app extension are running in different processes. There is no way to share one instance between the two. Each has to have their own instance of HKHealthStore.