gbesler gbesler - 1 year ago 106
iOS Question

How to return value in a block

I am trying to return a

value but its not returning the desired value. I was trying different variations but was not able to return the correct value. Here you can see how I try to reach it:

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

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
weightUnit = [HKUnit poundUnit];
usersWeight = [mostRecentQuantity doubleValueForUnit:weightUnit];
return usersWeight;

Answer Source

You call a block asynchronously. Th calling method returns, before the asynchronous block finished, so userWeight is unset and contains random data.

Instead of returning a value, you should pass a completion block to the method expecting the float value. Call this completion block at the end of your completion handler and pass the then computed userWeight. You do not need a local var outside the block.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download