我有一个应用程序,它有一个带有这个 viewDidLoad 的 tableviewcontroller:
- (void)viewDidLoad{
[super viewDidLoad];
// begin animating the spinner
[self.spinner startAnimating];
[SantiappsHelper fetchUsersWithCompletionHandler:^(NSArray *users) {
self.usersArray = [NSMutableArray array];
for (NSDictionary *userDict in users) {
[self.usersArray addObject:[userDict objectForKey:@"username"]];
}
//Reload tableview
[self.tableView reloadData];
}];
}
助手类方法是这样的:
+(void)fetchUsersWithCompletionHandler:(Handler)handler {
NSString *urlString = [NSString stringWithFormat:@"http://www.myserver.com/myApp/fetchusers.php"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
[request setHTTPMethod: @"GET"];
__block NSArray *usersArray = [[NSArray alloc] init];
//A
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
// Peform the request
NSURLResponse *response;
NSError *error = nil;
NSData *receivedData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (error) {
// Deal with your error
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
NSLog(@"HTTP Error: %d %@", httpResponse.statusCode, error);
return;
}
NSLog(@"Error %@", error);
return;
}
NSString *responseString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
usersArray = [NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSASCIIStringEncoding] options:0 error:nil];
if (handler){
dispatch_async(dispatch_get_main_queue(), ^{
handler(usersArray);
});
}
});
}
上面的代码是向我建议的,从我对 GCD 的了解来看,这很有意义。一切都在主队列上运行,但在 NSURLConnection 同步调用之前调度到后台队列之前。获取数据后,它会填充 usersArray 并将其返回到主队列。usersArray 已填充,当它测试 if 处理程序时,它移动到 dispatch_asynch(dispatch_get_main_queue () 行。但是当它返回主队列处理数组字典时,NSArray *users 为空。应用程序因此错误而崩溃:
* 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“* -[__NSArrayM insertObject:atIndex:]: object cannot be nil”
如果我注释掉 dispatch_async(dispatch_get_main_queue() 代码看起来像这样:
if (handler){
//dispatch_async(dispatch_get_main_queue(), ^{
handler(usersArray);
//});
}
它工作得很好......好吧,它有点迟钝。为什么会失败?