2016-11-02 4 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은 설정되어 있지 않으며 임의 데이터가 들어 있습니다.

값을 반환하는 대신 float 값을 예상하는 메서드에 완료 블록을 전달해야합니다. 완료 핸들러의 끝에이 완료 블록을 호출하고 계산 된 userWeight을 전달하십시오. 블록 외부에 지역 변수가 필요 없습니다.

1

는 아르 민에 따르면 나는 당신을 위해 예를 가지고 : dispatch_group_leave가 디스패치 그룹을 떠나 발생할 때까지 dispatch_group_wait가 대기 :

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

또 다른 가능성은 차단 방법을 만드는 것입니다.

하지만 메인 스레드에서이 메소드를 호출하지 않는 것이 좋습니다.

- (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; 
} 
관련 문제