我正在从服务器获取 JSON 格式的数据。它只有大约 150 条记录,我最初并没有使用 GCD,但是当我时不时地点击应用程序中的按钮以查看包含数据的表格时,它会延迟大约几秒钟,然后切换到表格视图并显示数据. 所以我实现了 GCD,现在当我点击按钮时,它会立即切换到 tableview,但是加载数据会有几秒钟的延迟,这似乎比 GCD 之前的实现要长。所以我不确定我是否正确使用了 GCD,或者是我的服务器导致了延迟(我认为这是罪魁祸首)。这是 GCD 在名为 retrieveData 的方法中的实现,我在 viewDidLoad 中将其称为 [self retrieveData]:
- (void)retrieveData
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
NSURL *url = [NSURL URLWithString:@"http://MY_URL/JSON/document.json"];
NSData * data = [NSData dataWithContentsOfURL:url];
dispatch_async(dispatch_get_main_queue(), ^{
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
//Set up our exhibitors array
exhibitorsArray = [[NSMutableArray alloc] init];
for (int i = 0; i < json.count; i++) {
//create exhibitors object
NSString * blabel = [[json objectAtIndex:i] objectForKey:@"BoothLabel"];
NSString * bName = [[json objectAtIndex:i] objectForKey:@"Name"];
NSString * bURL = [[json objectAtIndex:i] objectForKey:@"HyperLnkFldVal"];
exhibitors * myExhibitors = [[exhibitors alloc] initWithBoothName: bName andboothLabel: blabel andBoothURL: bURL];
//Add our exhibitors object to our exhibitorsArray
[exhibitorsArray addObject:myExhibitors];
//Sort by name
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
[exhibitorsArray sortUsingDescriptors:[NSMutableArray arrayWithObject:sort]];
}
[self.myTableView reloadData];
});
});
}