我正在尝试重构一些NSJSONSerialization
代码,使其不在主线程上。目前该应用程序有点迟钝。
我想将此代码重构为下面的代码,并且遇到语法问题,尤其是错误处理方面的问题。例如,如果我采用现有代码(requestData: 方法)并将其放入
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
});
该表不再加载任何数据。
谢谢你的帮助。
-(void)requestData {
[HUD showUIBlockingIndicatorWithText:@"Fetching JSON"];
NSError *requestError = nil;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
URLWithString:kURL]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&requestError];
NSError *jsonParsingError = nil;
if (requestError)
{
NSLog(@"sync. request failed with error: %@", requestError);
}
else
{
// handle data
publicData = [NSJSONSerialization JSONObjectWithData:response
options:0
error:&jsonParsingError];
publicDataArray = [publicData objectForKey:@"data"];
}
/*
for(publicDataDict in publicDataArray) {
NSLog(@"data output is %@",[publicDataDict objectForKey:@"title"]);
}
*/
[self.mainTableView reloadData];
[HUD hideUIBlockingIndicator];
}
这是我想使用的代码。
-(void)viewDidAppear:(BOOL)animated
{
[HUD showUIBlockingIndicatorWithText:@"Fetching Data"];
//1
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//code executed in the background
//2
NSData* ghData = [NSData dataWithContentsOfURL:
[NSURL URLWithString:kURL]
];
//3
NSDictionary* json = nil;
if (ghData) {
json = [NSJSONSerialization
JSONObjectWithData:ghData
options:kNilOptions
error:nil];
}
//4
dispatch_async(dispatch_get_main_queue(), ^{
//code executed on the main queue
//5
[self.tableView reloadData];
[HUD hideUIBlockingIndicator];
});
});
}