2016-06-25 2 views
0

iOS 앱에서 forecast.io API를 사용하여 3 일 특정 일기 예보를 얻습니다. 일단 내가 3에서 배열을 얻으면 NSMutableArray를 만들고 그 모든 객체를 추가하려고합니다. 내가 얻는 문제는 예측 데이터가 검색되기 전에 NSMutableArray를 생성하려고한다는 것이다. 는 예측 데이터 중 하나를 취득하기 전에다음 코드가 완료되기 전에 코드가 완료되지 않음

코드가 실행됩니다
typedef void(^myCompletion)(BOOL); 
-(void)viewWillAppear:(BOOL)animated { 
    [super viewWillAppear:YES]; 
    [self myMethod:^(BOOL finished) { 
     if(finished){ 
      NSMutableArray *allOfIt = [[NSMutableArray alloc] initWithObjects:self.weatherSaturday, self.weatherSunday, self.weatherMonday, nil]; 
      NSLog(@"%@", allOfIt); 
     } 
    }]; 

} 
-(void) myMethod:(myCompletion) compblock{ 
    //do stuff 
    ForecastKit *forecast = [[ForecastKit alloc] initWithAPIKey:@"MY-API-KEY"]; 
    // Request the forecast for a location at a specified time 
    [forecast getDailyForcastForLatitude:37.438905 longitude:-106.886051 time:1467475200 success:^(NSArray *saturday) { 

    // NSLog(@"%@", saturday); 
     self.weatherSaturday = saturday; 


    } failure:^(NSError *error){ 

     NSLog(@"Daily w/ time %@", error.description); 

    }]; 

    [forecast getDailyForcastForLatitude:37.438905 longitude:-106.886051 time:1467561600 success:^(NSArray *sunday) { 

     // NSLog(@"%@", sunday); 
     self.weatherSunday = sunday; 

    } failure:^(NSError *error){ 

     NSLog(@"Daily w/ time %@", error.description); 

    }]; 

    [forecast getDailyForcastForLatitude:37.438905 longitude:-106.886051 time:1467648000 success:^(NSArray *monday) { 

     // NSLog(@"%@", monday); 
     self.weatherMonday = monday; 

    } failure:^(NSError *error){ 

     NSLog(@"Daily w/ time %@", error.description); 

    }]; 

    compblock(YES); 
} 

, 그것은, 널 (null)로 표시 allOfIt에 대한 NSLog를, 화재 : 여기에 지금까지 가지고있는 것입니다. 내가 뭘 놓치고 있니?

답변

2

문제 내가 얻고는 예측 데이터가 정확하게

그래를 검색하기 전에가있는 NSMutableArray를 만들기 위해 노력하고 있다는 점이다. 문제는 단순히 "비동기"가 무엇을 의미하는지 이해하지 못한다는 것입니다. 네트워킹에 걸리는 시간은이며 모두 백그라운드에서 발생합니다. 한편 주 코드 을 일시 중지하지 않습니다. 그것은 모두 즉시 실행됩니다.

따라서 코드를 작성한 순서대로 발생하지는 않습니다. 세 번 모두 getDailyForcastForLatitude 호출은 즉시 중지되고 전체 메소드가 종료됩니다. 그런 다음 천천히 하나씩 차례대로 서버를 호출하고 세 개의 완료 핸들러 (중괄호 안에있는 물건)가 호출됩니다. 당신이 완료 핸들러가 순서대로 호출하려는 경우

, 당신은 앞에있는 getDailyForcastForLatitude 호출의 완료 핸들러에 을 할 각 getDailyForcastForLatitude 전화를해야합니다. 또는 완성 처리기가 언제 어떤 순서로 반환되는지는 중요하지 않은 방식으로 코드를 작성하십시오.

+0

3 개의 메시지가 모두 서버로 이동하여 동시에 되돌아 오기 때문에 후자는 대개 훨씬 빠릅니다. – gnasher729