维护 HKHealthStore 对象的最佳方法......单例?
Best approach for maintaining a HKHealthStore object...Singleton?
我意识到单例并不总是首选,但是在使用 HealthKit 时根据 Apple 文档 "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."
为了在每个应用程序会话中保留 1 个 HKHealthStore 而在此处使用单例是否有任何缺点(与在不同 classes 中实例化多个 HKHealthStores 或尝试传递同一实例相反) ?
其次,为 iPhone 应用程序和 Watch Extension 提供单独的 Singleton class 是否更可取?或者两者都可以使用单个 Singleton class?
import Foundation
import HealthKit
class HealthStoreSingleton {
class var sharedInstance: HealthStoreSingleton {
struct Singleton {
static let instance = HealthStoreSingleton()
}
return Singleton.instance
}
let healthStore = HKHealthStore()
}
我发现如果您正在使用锚定更新查询,那么您应该意识到您的 HealthStore 被阻塞,直到您的 updateHandler 函数 returns。因此,您不能使用 updateHandler 中的 HealthStore 单例。
您可以通过在操作队列上使用并发:队列操作,并在开始处理操作之前从您的 updateHandler return 来解决此问题。
或者您可以创建第二个 HealthStore 实例,并从 updateHandler 内部使用它。我必须说我做了一些实验以了解它是否有效,但我并没有在现实生活中使用这个方案。所以我不知道性能影响。
关于您的第二个问题:应用程序和应用程序扩展 运行 在不同的进程中。无法在两者之间共享一个实例。每个人都必须有自己的 HKHealthStore 实例。
我意识到单例并不总是首选,但是在使用 HealthKit 时根据 Apple 文档 "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."
为了在每个应用程序会话中保留 1 个 HKHealthStore 而在此处使用单例是否有任何缺点(与在不同 classes 中实例化多个 HKHealthStores 或尝试传递同一实例相反) ?
其次,为 iPhone 应用程序和 Watch Extension 提供单独的 Singleton class 是否更可取?或者两者都可以使用单个 Singleton class?
import Foundation
import HealthKit
class HealthStoreSingleton {
class var sharedInstance: HealthStoreSingleton {
struct Singleton {
static let instance = HealthStoreSingleton()
}
return Singleton.instance
}
let healthStore = HKHealthStore()
}
我发现如果您正在使用锚定更新查询,那么您应该意识到您的 HealthStore 被阻塞,直到您的 updateHandler 函数 returns。因此,您不能使用 updateHandler 中的 HealthStore 单例。
您可以通过在操作队列上使用并发:队列操作,并在开始处理操作之前从您的 updateHandler return 来解决此问题。
或者您可以创建第二个 HealthStore 实例,并从 updateHandler 内部使用它。我必须说我做了一些实验以了解它是否有效,但我并没有在现实生活中使用这个方案。所以我不知道性能影响。
关于您的第二个问题:应用程序和应用程序扩展 运行 在不同的进程中。无法在两者之间共享一个实例。每个人都必须有自己的 HKHealthStore 实例。