2016-11-02 6 views
-2

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; 
} 
+0

元のメソッドの補完ブロックを使用して、その後、希望の値でそのブロックをコールバックすることができます。 – holex

答えて

1

ブロックを非同期に呼び出します。呼び出しメソッドは、非同期ブロックが終了する前に戻りますので、userWeightは設定されておらず、ランダムなデータが含まれています。

値を返す代わりに、浮動小数点値を期待するメソッドに完了ブロックを渡す必要があります。完了ハンドラの最後にこの完了ブロックを呼び出し、計算したuserWeightを渡します。ブロックの外側にローカル変数は必要ありません。

1

アーミンによると、私はあなたのための例があります。

- (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_leaveは、ディスパッチグループを離れる原因となるまで dispatch_group_waitをお待ちしております。

ただし、メインスレッドでこのメソッドを呼び出さないほうがよいことに注意してください。

- (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; 
} 
関連する問題