我對iOS中的Web服務調用和線程是一種新手。我的應用程序中包含一個ViewController
,其中包含一個tableview控件。我使用通過JSON Web服務獲取的數據填充表格。 JSON Web服務在其自己的線程中調用,在此期間我填充NSArray
和NSDictionary
。範圍和線程在iOS中
我的數組和字典好像超出了範圍,因爲我的NSLog
語句對於數組計數返回零,即使在fetchedData
中數組已完全填充。
有人可以解釋爲什麼我的數組和字典對象在線程之外是空的嗎?
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *serviceEndpoint = [NSString stringWithFormat:
@"http://10.0.1.12:8888/platform/services/_login.php?un=%@&pw=%@&ref=%@",
[self incomingUsername], [self incomingPassword], @"cons"];
NSURL *url = [NSURL URLWithString:serviceEndpoint];
dispatch_async(kBgAdsQueue, ^{
NSData *data = [NSData dataWithContentsOfURL:url];
[self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
});
NSLog(@"ARRAY COUNT: %d\n", [jsonArray count]);
}
-(void)fetchedData:(NSData*)responseData{
NSError *error;
jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
jsonArray = [[jsonDict allKeys]sortedArrayUsingSelector:@selector(compare:)];
for(NSString *s in jsonArray){
NSLog(@"%@ = %@\n", s, [jsonDict objectForKey:s]);
}
}
'ViewDidLoad'只在屏幕第一次加載時被調用。你確定'fetchedData'在此之前被調用嗎? – thegrinner 2013-04-23 13:43:44