2013-03-13 72 views
0

我的程序工作的方式是通過AFHTTPClient將數據拉入程序。然後我得到我的回覆數據。然後我將這些數據通過NSJSONSerialization解析成一個NSMutableArray。這個數組用來填充一個UIPickerView。奇怪的錯誤與NSJSONSerialization和UIPIckerView

此方法在用戶打開應用程序或按下刷新按鈕時觸發。問題是當應用程序打開時,通話已完成,並且我收回數據。如果我去選取器,它似乎是空的,但當你向下滾動時,5的底部2是在那裏,當你回滾了其他人也進來。如果在任何時候我按下刷新按鈕,錯誤消失,並且選取器被正確填充。爲什麼它不能正常工作的任何原因?每次通話後,我都會重新加載所有組件。

-(void) getData{ 
// Paramaters 
NSString *lat = @"40.435615"; 
NSString *lng = @"-79.987872"; 
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: lat, @"lat", lng, @"lng", nil]; 

// posting the data and getting the response 
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://mysite.com/"]]; 
[client postPath:@"/mypostpath.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { 
    NSString *text = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; 
    NSLog(@"Response: %@", text); 

    NSError *error; 
    json = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error]; 

    // setting the first location to the text feild 
    NSDictionary* name = [json objectAtIndex:0]; 
    locationField.text = [name objectForKey:@"name"]; 

} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    NSLog(@"%@", [error localizedDescription]); 
}]; 


// reload the picker 
[pickerCust reloadAllComponents]; 

// setting the first location to the text feild 
NSDictionary* name = [json objectAtIndex:0]; 
locationField.text = [name objectForKey:@"name"]; 

}

回答

1

的問題是,因爲[pickerCust reloadAllComponents];正在加載數據結束塊之前調用。將呼叫轉移到success區塊。

由於它與UI組件交互,因此將其包裝在dispatch_async中,以便它在主隊列上運行。

dispatch_async(dispatch_get_main_queue(), ^{ 
    [pickerCust reloadAllComponents]; 
}); 
+0

究竟做dispatch_async(dispatch_get_main_queue()有什麼不同? – JohnV 2013-03-13 19:53:04

+1

到UI所有的更新都應該是主線程上進行的。該塊在不同的線程執行。在'dispatch_async'將迫使它的內容在主線程上運行,以便UI更新正確 – 2013-03-13 20:21:51

+0

謝謝!這是完全合理的,從現在開始我必須使用它 – JohnV 2013-03-14 02:06:52