此代码加载表视图:
- (void)viewDidLoad { [super viewDidLoad]; //test data NSURL *url =[[NSURL alloc] initWithString:urlString]; // NSLog(@"String to request: %@",url); [ NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc]initWithURL:url] queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { if([data length] >0 && connectionError ==nil){ NSArray *arrTitle=[[NSArray alloc]init]; NSString *str=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; arrTitle= [Helper doSplitChar:[Helper splitChar20] :str]; self.tableView.delegate = self; self.tableView.dataSource = self; [self fecthDataToItem:arrTitle]; [self.tableView reloadData]; NSLog(@"Load data success"); }else if (connectionError!=nil){ NSLog(@"Error: %@",connectionError); } }]; // arrTitle = [NSArray arrayWithObjects:@"ee",@"bb",@"dd", nil]; }
加载需要10到15秒.我怎样才能让它更快?.谢谢Rob和rmaddy,问题解决了.
正如rmaddy指出的那样,您必须在主队列上进行UI更新.否则,将会解决您遇到的一些问题.
该queue
参数sendAsynchronousRequest
表示要在其完成块的运行队列.所以,您可以简单地指定[NSOperationQueue mainQueue]
:
NSURLRequest *request = [NSURLRequest requestWithURL:url]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { if([data length] > 0 && connectionError == nil) { NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSArray *arrTitle = [Helper doSplitChar:[Helper splitChar20] :str]; self.tableView.delegate = self; self.tableView.dataSource = self; [self fecthDataToItem:arrTitle]; [self.tableView reloadData]; } else if (connectionError!=nil) { NSLog(@"Error: %@",connectionError); } }];
或者,如果您在该块中执行某些操作较慢或计算成本较高/较慢的情况,请继续使用您自己的后台队列,然后将UI更新分发回主队列,例如:
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { // do something computationally expensive here // when ready to update the UI, dispatch that back to the main queue [[NSOperationQueue mainQueue] addOperationWithBlock:^{ // update your UI here }]; }];
无论哪种方式,您都应该始终在主队列上进行UI更新(也可能是模型更新,以保持同步).