在 iOS 上高效解析 HealthKit 的 HKSampleQuery 结果
Efficiently parse HKSampleQuery results for HealthKit on iOS
我的应用程序使用 HealthKit 框架来检索用户健康数据。我想从 HealthKit 获得大约 25 个不同的数据点。
为此,我目前在示例查询的完成处理程序内的 for-loop
中进行了 25 次调用。 有什么方法可以合并结果,或者更有效地执行此过程?。
据我所知,我必须这样做(请参阅下面的代码)。提前谢谢你。
NSDate *startDate, *endDate;
// Use the sample type for step count
HKSampleType *sampleType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
// Create a predicate to set start/end date bounds of the query
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictStartDate];
// Create a sort descriptor for sorting by start date
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:YES];
HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:predicate limit:HKObjectQueryNoLimit sortDescriptors:@[sortDescriptor] resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
if (!error && results) {
for (HKQuantitySample *samples in results) {
// your code here
}
}
}];
// Execute the query
[healthStore executeQuery:sampleQuery];
您应该并行执行查询。
这使 HealthKit 能够高效地执行您的查询。
如果您这样做,HealthKit 会为您进行优化。
执行此操作的最优雅和可读的方法可能是循环。
但是写 25 行也是一样的。
您无需执行任何操作即可将查询放入后台队列。 HealthKit 为您做这件事。
有时您会收到 25 次回电。
我的应用程序使用 HealthKit 框架来检索用户健康数据。我想从 HealthKit 获得大约 25 个不同的数据点。
为此,我目前在示例查询的完成处理程序内的 for-loop
中进行了 25 次调用。 有什么方法可以合并结果,或者更有效地执行此过程?。
据我所知,我必须这样做(请参阅下面的代码)。提前谢谢你。
NSDate *startDate, *endDate;
// Use the sample type for step count
HKSampleType *sampleType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
// Create a predicate to set start/end date bounds of the query
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictStartDate];
// Create a sort descriptor for sorting by start date
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:YES];
HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:predicate limit:HKObjectQueryNoLimit sortDescriptors:@[sortDescriptor] resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
if (!error && results) {
for (HKQuantitySample *samples in results) {
// your code here
}
}
}];
// Execute the query
[healthStore executeQuery:sampleQuery];
您应该并行执行查询。 这使 HealthKit 能够高效地执行您的查询。 如果您这样做,HealthKit 会为您进行优化。 执行此操作的最优雅和可读的方法可能是循环。 但是写 25 行也是一样的。
您无需执行任何操作即可将查询放入后台队列。 HealthKit 为您做这件事。
有时您会收到 25 次回电。