Class

HKCorrelationQuery

A query that performs complex searches based on the correlation’s contents, and returns a snapshot of all matching samples.

Declaration

@interface HKCorrelationQuery : HKQuery

Overview

Correlation samples act as a container, grouping multiple quantity or category samples. While you can use HKSample objects to search for correlations, correlation queries allow more complex filtering based on the contained samples. Specifically, correlation queries let you provide a separate predicate for each of the sample types stored in the correlation. A correlation is returned only if the correlation’s predicate and all of the sample predicates match.

Requesting Permission to Share and Read

Unlike other sample types, you do not request permission to share and read correlation types directly. Instead, you request permission to share and read each of the sample types contained within the correlation.

When saving a correlation, the app must have permission to share all of the contained objects. If the app does not have permission to share one or more of the contained objects, the operation fails.

When your app queries for correlation data, HealthKit only returns samples that contain objects you have permission to read. If the app has permission to read only some of the contained objects, HealthKit still returns the correlation; however, the correlation appears to only contain those objects that your app has permission to read. HealthKit hides all of the other contained objects from your app.

Executing Queries

You create a correlation query by calling the initWithType:predicate:samplePredicates:completion: initializer. After the query is instantiated, you run it by calling the HealthKit store’s executeQuery: method. This method runs the query on an anonymous background queue. When the query is complete, it executes the results handler on the same background queue (though not necessarily the same thread). Typically, you dispatch these results back to the main thread to update your user interface.

Listing 1 builds a correlation query that searches for food samples with more than 800 calories.

Listing 1

Searching for high calorie food

NSMutableArray *highCalorieFoods = [NSMutableArray array];
HKQuantity *highCalorie = [HKQuantity quantityWithUnit:[HKUnit kilocalorieUnit]
                                           doubleValue:800.0];
 
NSPredicate *greaterThanHighCalorie =
[HKQuery predicateForQuantitySamplesWithOperatorType:
 NSGreaterThanOrEqualToPredicateOperatorType quantity:highCalorie];
 
HKQuantityType *energyConsumed =
[HKObjectType quantityTypeForIdentifier:
 HKQuantityTypeIdentifierDietaryEnergyConsumed];
 
NSDictionary *samplePredicates = @{energyConsumed : greaterThanHighCalorie};
 
HKCorrelationType *foodType =
[HKCorrelationType correlationTypeForIdentifier:HKCorrelationTypeIdentifierFood];
 
HKCorrelationQuery *query =
[[HKCorrelationQuery alloc]
 initWithType:foodType predicate:nil
 samplePredicates:samplePredicates
 completion:^(HKCorrelationQuery *query, NSArray *correlations, NSError *error) {
     if (correlations == nil) {
         // Provide proper error handling here...
         NSLog(@"An error occurred while searching for high calorie food: %@",
              error.localizedDescription);
         abort();
     }
     for (HKCorrelation *correlation in correlations) {
         [highCalorieFoods addObject:correlation];
     }
     NSLog(@"Found %lu foods: %@", (unsigned long)[highCalorieFoods count], highCalorieFoods);
 
 }];
 
[self.healthStore executeQuery:query];

Listing 1 begins by setting up an array to store our high calorie foods. Next, the sample code creates a predicate that matches quantities greater than or equal to 800 kcal. It then creates a dictionary using a quantity type object for dietary energy consumed as the key and the newly-created predicate as the value. It uses this dictionary as the sample predicates for a correlation query.

In the query’s completion handler, the sample code first checks to see if an error occurred. If no errors occurred, it adds the results to the array of high calorie foods. Then it logs the number of matching samples found, and the contents of the high calorie foods array.

Once the sample code finishes declaring the completion handler, the query is ready to use. The sample code simply executes the query on the HeathKit store.

Subclassing Correlation Queries

Like many HealthKit classes, the HKCorrelationQuery class should not be subclassed.

Topics

Creating Correlation Queries

- initWithType:predicate:samplePredicates:completion:

Instantiates and returns a correlation query.

Getting Property Data

correlationType

The type of correlation to search for.

samplePredicates

A dictionary whose keys are HKSampleType instances and whose values are NSPredicate instances.

Relationships

Inherits From

See Also

Common Query Types

HKSampleQuery

A general-purpose query that returns a snapshot of all the matching samples currently saved in the HealthKit store.

HKQuantitySeriesSampleQuery

A query that accesses the series data associated with a quantity sample.

HKAnchoredObjectQuery

A query that returns only recent changes to the HealthKit store, including a snapshot of new changes and continuous monitoring as a long-running query.

HKObserverQuery

A long-running query that monitors the HealthKit store and updates your app when the HealthKit store saves or deletes a matching sample.

HKDocumentQuery

A query that returns a snapshot of all matching documents currently saved in the HealthKit store.

HKHeartbeatSeriesQuery

A query that returns the heartbeat data contained in a heartbeat series sample.

HKQuery

An abstract class for all the query classes in HealthKit.