使用不同的变量异步运行某些代码

时间:2016-02-16 11:28:28

标签: ios objective-c iphone health-kit hksamplequery

所以,我试图让我的应用程序读入HealthKit数据。我有一个函数,我从主应用程序视图控制器调用,导致在另一个类中查询该月的所有健康数据。然后在数据数组从计算类中的单独函数返回到视图控制器中的单独函数之前进行一些计算。

由于数据量的原因,查询大约需要2秒钟。我希望能够异步设置它们,当它们全部返回时,我可以更新UI。

问题是,我每月调用该函数,然后启动HKSampleQueries,但它们不会按顺序返回,并且它们返回的时间会有所不同。这意味着我最终会在一组数据计算中途改变变量,因为下一组刚刚开始。

我只知道两种方法:

在调用每个计算之前设置延迟:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{}

但这浪费了应用时间

或者我可以多次复制代码并为每个月调用不同的类。但这似乎是愚蠢和低效的。

所以问题是。如何有效地共享每次使用不同变量运行多次的代码。 干杯

功能示例:

在View控制器中:

HeartRateCalculator *commonClassTwo =[[HeartRateCalculator alloc] init];
[commonClassTwo calculateData:0];
[commonClassTwo calculateData:-1];
[commonClassTwo calculateData:-2];

在HeartRateCalculator

-(void)calculateData:(NSInteger)monthsBack{
  //Some other stuff
//Generate monthPeriodPredicate based on monthsBack integer
  HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:heartRate predicate:monthPeriodPredicate limit:200000 sortDescriptors:@[timeSortDescriptor] resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
  //Finish Calculations, call other functions (ie. [self doThis];) and then return
//When calculations return, monthPeriodPredicate is always value of the last predicate to be called, not the one that the HKSampleQuery was made with.
}
[healthStoreFive executeQuery:query];

完整代码:

-(void)calculateData:(NSInteger)monthsBack withCompletionBlock:(void(^)())completionBlock {//0 Means only current month, 2 means this month and last month and month before
//for(NSInteger i=0; i>=monthsBack; i--){
    //monthForCalculation = monthsBack;
    NSDateComponents *components = [[NSCalendar currentCalendar] components: NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:[NSDate date]];
    NSDateComponents *adjustableComponent = [[NSDateComponents alloc] init];
    [adjustableComponent setMonth:monthsBack];
    [adjustableComponent setDay:-[components day]+1];
    [adjustableComponent setHour:-[components hour]];
    [adjustableComponent setMinute:-[components minute]];
    [adjustableComponent setSecond:-[components second]];
    startOfMonth = [[NSCalendar currentCalendar] dateByAddingComponents:adjustableComponent toDate:[NSDate date] options:0];
    adjustableComponent = [[NSDateComponents alloc] init];
    [adjustableComponent setMonth:1];
    NSDate *endOfMonth = [[NSCalendar currentCalendar] dateByAddingComponents:adjustableComponent toDate:startOfMonth options:0];

    NSDate *secondEarlier = [endOfMonth dateByAddingTimeInterval:-1];
    components = [[NSCalendar currentCalendar] components: NSCalendarUnitDay fromDate:secondEarlier];
    daysInMonth = [components day];

    NSPredicate *monthPeriodPredicate = [HKQuery predicateForSamplesWithStartDate:startOfMonth endDate:endOfMonth options:HKQueryOptionStrictStartDate];
    healthStoreFive = [[HKHealthStore alloc] init];
    HKQuantityType *heartRate = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];
    NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate ascending:NO];
    HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:heartRate predicate:monthPeriodPredicate limit:200000 sortDescriptors:@[timeSortDescriptor] resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
        NSMutableArray *dataValues = [[NSMutableArray alloc] init];
        NSMutableArray *dataDates = [[NSMutableArray alloc] init];
        for (HKQuantitySample *sample in results) {
            [dataValues addObject:[NSNumber numberWithFloat:[sample.quantity doubleValueForUnit:[[HKUnit countUnit] unitDividedByUnit:[HKUnit minuteUnit]]]]];
            [dataDates addObject:sample.startDate];
        }
        monthForCalculation = monthsBack;
        chronologicalDataValues = [[NSMutableArray alloc] init];
        chronologicalDataDates = [[NSMutableArray alloc] init];
        chronologicalDataValues = [[[dataValues reverseObjectEnumerator] allObjects] mutableCopy];
        chronologicalDataDates = [[[dataDates reverseObjectEnumerator] allObjects] mutableCopy];          
        //dispatch_async(dispatch_get_main_queue(), ^{
            if(dataDates.count == 0){
                ViewController *commonClass =[[ViewController alloc] init];
                [commonClass receiveCalculationData:[[NSMutableArray alloc] init] array:[[NSMutableArray alloc] init] daysToDisplay:[[NSMutableArray alloc] init] chosenMonth:monthForCalculation];
            }
            else{
                NSLog(@"%@", [dataDates objectAtIndex:dataDates.count-1]);
                NSLog(@"%@", [dataDates objectAtIndex:0]);
                [self calculateDayStringsFromData];
            }

            completionBlock();
        //});
    }];
    NSLog(@"HKSampleQuery Requested For Heart Rate Data");
    [healthStoreFive executeQuery:query];

//}     }

3 个答案:

答案 0 :(得分:2)

使用block

[commonClassTwo calculateData:0 withCompletionBlock:^{
    [commonClassTwo calculateData:-1 withCompletionBlock:^{
        [commonClassTwo calculateData:-2 withCompletionBlock:^{
            NSLog(@"All 3 calculation done");
        }];
    }];
}];
- (void)calculateData:(NSInteger)monthsBack withCompletionBlock:(void(^)())completionBlock {
    //Some other stuff
    HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:heartRate predicate:monthPeriodPredicate limit:200000 sortDescriptors:@[timeSortDescriptor] resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
        //Finish Calculations, call other functions (ie. [self doThis];) and then return
        completionBlock();
    }
    [healthStoreFive executeQuery:query];
}

<强>更新

对于异步调用,请将计数器设为integer。初始值将是您想要的异步调用数。 (此处3)
在每次通话的完成时,递减计数器并检查所有通话是否完成。
如果完成更新UI

[commonClassTwo calculateData:0 withCompletionBlock:^{
    // counter--;
    // [self updateUI];
}];

[commonClassTwo calculateData:-1 withCompletionBlock:^{
    // counter--;
    // [self updateUI];
}];

[commonClassTwo calculateData:-2 withCompletionBlock:^{
    // counter--;
    // [self updateUI];
}];


- (void)updateUI {
    // if counter == 0 {
    //     dispatch_async(dispatch_get_main_queue(), ^{
    //         update UI
    //     });
    // }
}

答案 1 :(得分:2)

您可以使用dispatch_group来安排在完成所有任务后触发阻止。

您只需要修改calculateData:方法以接受dispatch_group_t参数(如果需要,您也可以随时添加完成块):

- (void)calculateData:(NSInteger)monthsBack group:(dispatch_group_t)group {

    dispatch_group_enter(group); // increment group task count

    //Some other stuff

    HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:heartRate predicate:monthPeriodPredicate limit:200000 sortDescriptors:@[timeSortDescriptor] resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {

        //Finish Calculations, call other functions (ie. [self doThis];) and then return

        dispatch_group_leave(group); // decrement task count
    }];

    [healthStoreFive executeQuery:query];

}

然后你就可以这样称呼它:

HeartRateCalculator *commonClassTwo =[[HeartRateCalculator alloc] init];

dispatch_group_t group = dispatch_group_create();

[commonClassTwo calculateData:0 group:group];
[commonClassTwo calculateData:-1 group:group];
[commonClassTwo calculateData:-2 group:group];

dispatch_group_notify(group, dispatch_get_main_queue(), ^{ // called when all tasks are finished.
    // update UI
});

Warif was going for相同的原则,但dispatch_groups 比使用自己的变量跟踪执行任务的数量更优雅。

虽然当您说您希望异步执行任务时,我不确定您的意思。来自Apple docs on HKSampleQuery

  

查询在匿名后台队列上运行。

因此,您的任务已经异步。

答案 2 :(得分:0)

您可以改为创建单独的类并同时运行它们。

HeartRateCalculator *commonClassOne =[[HeartRateCalculator alloc] init];
HeartRateCalculator *commonClassTwo =[[HeartRateCalculator alloc] init];
HeartRateCalculator *commonClassThree =[[HeartRateCalculator alloc] init];
[commonClassOne calculateData:0];
[commonClassTwo calculateData:-1];
[commonClassThree calculateData:-2];

这样您就不必复制代码,但他们不会覆盖同一类中的值。