在苹果文档中,它说有些实例需要在每个应用程序中创建一次,比如HKHealthStore:
每个应用程序只需要一个HealthKit商店。这些都是长寿的物体。创建一次存储,并保留一个参考资料供以后使用。
做一些像安全下面这样方便的事情,还是有更好的方法?
public extension HKHealthStore {
class var sharedInstance: HKHealthStore? {
if !HKHealthStore.isHealthDataAvailable() {
return nil
}
struct Singleton {
static let instance = HKHealthStore()
}
return Singleton.instance
}
}这样,我就可以在不污染自定义管理器的情况下做到这一点:HKHealthStore.shareInstance?.requestAuthorizationToShareTypes
这样可以吗?还是有一种更好的架构方法?
发布于 2016-02-24 16:56:44
我会这样做:
class MyHealthStore:HKHealthStore {
static let sharedInstance = MyHealthStore()
}现在您可以使用MyHealthStore.sharedInstance,它将始终返回相同的存储。
您也可以在没有子类的情况下实现相同的目标:
class MyCustomClass:NSObject {
static let sharedInstance = MyCustomClass()
let healthStore = HKHealthStore()
}现在你可以使用MyCustomClass.sharedInstance.healthStore了
https://stackoverflow.com/questions/35591466
复制相似问题