【发布时间】:2013-01-17 02:44:43
【问题描述】:
我正在尝试使用情节提要和 JSON 创建一个松散版本的 LazyTabelImages。在我的主 TableViewController 上的 ViewDidLoad 中,我启动了一个 NSURLConnection 来获取 JSON 数据,但是直到连接完成后我的单元格才会加载。我想要与 LazyTableImages 相同的行为,其中单元格加载为空白,然后填充信息(重新加载表数据)。如果我不使用故事板,我可以复制它,因为 LazyTables 不使用故事板,但这不是一个选项。
我已经查看了 LazyTableImages 以尝试找到解决方案,但情节提要有很大的不同(无论如何对我来说)。
有没有一种简单的方法可以让单元格加载为空白?例如,如果设备没有互联网,我仍然希望我的 TableView 显示出来,我会在单元格中放置一条自定义消息。
代码:
我在 viewDidLoad 中初始化连接的部分......
NSURLRequest *urlrequest = [NSURLRequest requestWithURL:[NSURL URLWithString:serverURL]];
self.dataConnection = [[NSURLConnection alloc] initWithRequest:urlrequest delegate:self];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
connectionDidFinnishLoading...
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//ListData below is an array that my data received (JSON) is loaded into. It is then passed to getTableData.
self.dataConnection = nil;
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self performSelectorOnMainThread:@selector(getTableData:) withObject:ListData waitUntilDone:YES];
});
}
getTableData...
-(void)getTableData:(NSData *)jsonData
{
NSError *error = nil;
arrayEntries = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&error];
for (int x = 0; x < arrayEntries.count; x++)
{
NSMutableDictionary *dic = [arrayEntries objectAtIndex:x];
//ARecord is a class just like in LazyTableImages that creates objects to keep the icons/data together. The ARecords are loaded into the TableView
ARecord *arecord = [[ARecord alloc] init];
NSString *title = [dic objectForKey:@"title"];
NSString *subt = [dic objectForKey:@"subtitle"];
NSString *url = [dic objectForKey:@"image_URL"];
arecord.Icon = nil;
arecord.URL = url;
arecord.Name = title;
arecord.title = subt;
//this is where I load an array full of the arecord objects.
[array addObject:arecord];
}
[self.tableView reloadData];
}
【问题讨论】:
-
你在主线程调用网络了吗?如果是这样,网络阻塞 UI 线程。
-
我曾尝试使用 GCD 将其移出主线程,但随后我只得到一个白屏,因为表永远不会加载。 NURLConnection 中有一个 GCD 调用,用于处理不同线程上的 JSON 解析。
-
请注意,您的 NSURLConnection (应该)已经是异步的。将其移至后台线程可能是个坏主意。正如 Quinn 所说,在涉及网络的地方“Threads Are Evil™”。
-
我也记得,但不管我怎么剪;要么将 NSURLConnection 移至后台线程,要么将解析移至后台线程,在 NSURLConnection 完成之前不会加载单元格。我需要将初始下载移出 UI。
-
你已经使用了asyn newworking,所以不需要使用gcd。
标签: iphone uitableview nsurlconnection