如何在块中返回值

时间:2016-11-02 11:54:49

标签: ios objective-c xcode

我正在尝试返回double值,但它没有返回所需的值。我尝试了不同的变化,但无法返回正确的值。在这里你可以看到我如何尝试达到它:

- (double)readData
{
    __block double usersWeight;
    HKQuantityType *weightType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];
    [self.healthStore aapl_mostRecentQuantitySampleOfType:weightType predicate:nil completion:^(HKQuantity *mostRecentQuantity, NSError *error) {
    if (!mostRecentQuantity) {
        NSLog(@"%@",error);

        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"Not Available");
        });
    }
    else {
        // Determine the weight in the required unit.
        HKUnit *weightUnit;

        if([strWeightUnit isEqualToString:@"kgs"])
        {
            weightUnit = [HKUnit gramUnit];
            usersWeight = [mostRecentQuantity doubleValueForUnit:weightUnit];
            usersWeight = usersWeight / 1000.0f; //kg value
        }
        else
        {
            weightUnit = [HKUnit poundUnit];
            usersWeight = [mostRecentQuantity doubleValueForUnit:weightUnit];
        }
    }
}];
return usersWeight;
}

2 个答案:

答案 0 :(得分:1)

您异步调用块。在异步块完成之前,Th调用方法返回,因此userWeight未设置并包含随机数据。

您应该将完成块传递给期望浮点值的方法,而不是返回值。在完成处理程序结束时调用此完成块并传递随后计算的userWeight。你不需要在块外面使用局部变量。

答案 1 :(得分:1)

根据Armin,我有一个例子给你:

- (void)readDataCompletion:(void (^)(double))completion
{
    HKQuantityType *weightType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];
    [self.healthStore aapl_mostRecentQuantitySampleOfType:weightType
                                                predicate:nil
                                               completion:^(HKQuantity *mostRecentQuantity,
                                                            NSError *error)
    {
        ...
        completion(weight);
    }];
}

另一种可能性是创建阻止方法: dispatch_group_wait会等到dispatch_group_leave离开调度组。

但请记住最好不要在主线程上调用此方法。

- (double)readData
{
    dispatch_group_t g = dispatch_group_create();
    dispatch_group_enter(g);

    __block double weight = 0;
    HKQuantityType *weightType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];
    [self.healthStore aapl_mostRecentQuantitySampleOfType:weightType
                                                predicate:nil
                                               completion:^(HKQuantity *mostRecentQuantity,
                                                            NSError *error)
     {
         weight = 123;
         dispatch_group_leave(g);
     }];

    dispatch_group_wait(g, DISPATCH_TIME_FOREVER);
    return weight;
}