我通过同步方法从Web服务获取数据。我向Web服务发出请求,然后查看冻结。我尝试在从Web服务加载数据之前添加UIActivityIndicatorView,并在获取数据后停止它,但不显示活动指示符。 我试图将Web服务数据获取操作放在不同的线程上
[NSThread detachNewThreadSelector:@selector(fetchRequest) toTarget:self withObject:nil];
但此时TableView崩溃,因为它没有获取绘制单元格的数据。 在fetchRequest函数中我正在做什么
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
URLWithString:URLString]];
NSData *response = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSError *jsonParsingError = nil;
NSDictionary *tableData = [NSJSONSerialization JSONObjectWithData:response
options:0
error:&jsonParsingError];
responseArray = [[NSMutableArray alloc]initWithArray:[tableData objectForKey:@"data"]];
for(int i = 0; i < responseArray.count; i++)
{
NSArray * tempArray = responseArray[i];
responseArray[i] = [tempArray mutableCopy];
}
此responseArray
用于填充单元格中的信息
请告诉我怎么做。任何帮助将不胜感激......
答案 0 :(得分:2)
问题在于你的方法。 Synchronous
方法在主线程上运行。并且由于主线程上的UI更新,您的应用挂起。
因此,解决方案是使用asynchronous
方法在单独的线程上下载数据,这样您的用户界面就不会挂起。
因此,请使用NSURLConnection
的{{1}}。这是一些示例代码:
sendAsynchronousRequest
答案 1 :(得分:1)
你最好使用Grand Central Dispatch来获取这样的数据,这样你就可以在后台队列中调度它,并且不会阻塞也用于UI更新的主线程:
dispatch_queue_t myqueue = dispatch_queue_create("myqueue", NULL);
dispatch_async(myqueue, ^(void) {
[self fetchRequest];
dispatch_async(dispatch_get_main_queue(), ^{
// Update UI on main queue
[self.tableView reloadData];
});
});
关于您可以在解析开始时使用的活动指示器:
[self.activityIndicator startAnimating];
self.activityIndicator.hidesWhenStopped = YES
然后当你的表填满数据时:
[self.activityIndicator stopAnimating];