我目前正在UITableViewController的viewDidLoad方法中加载来自
JSON服务的数据.问题是数据需要时间来检索和解析,视图需要时间来创建.
加载此数据的最佳位置在哪里?我假设在创建视图后有一个钩子在某处加载数据.通过这样做,我将能够在最终视图中使用一些UIActivityIndicatorView.
谢谢
加载此数据的最佳位置在哪里?我假设在创建视图后有一个钩子在某处加载数据.通过这样做,我将能够在最终视图中使用一些UIActivityIndicatorView.
谢谢
解决方法
最后这里有一个基于注释的解决方案:在viewDidLoad中启动一个线程来获取数据而不阻塞所有:
- (void) viewDidLoad { dataLoaded = NO; [self initSpinner]; [self launchLoadData]; ... } -(void)launchLoadData { NSLog(@"Launching thread"); [NSThread detachNewThreadSelector:@selector(loadData) toTarget:self withObject:nil]; } - (void) loadData { dataLoaded = NO; NSLog(@" thread launched"); NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self loadDataFromURL:nil]; dataLoaded = YES; [self.tableView reloadData]; [pool release]; } - (void)loadDataFromURL:(NSString*)url { // start the spinner to show that loading may be time consuming... [NSThread detachNewThreadSelector: @selector(spinBegin) toTarget:self withObject:nil]; JSONLoader *loader = [[JSONLoader alloc] init]; self.accounts = [loader getAccountsFromURL:@"http://foo/bar/repository.json"]; [loader release]; //[NSThread sleepForTimeInterval:3]; [NSThread detachNewThreadSelector: @selector(spinEnd) toTarget:self withObject:nil]; }
并使用该标志显示或不显示表中的数据.从线程调用时,tableView reloadData将完成剩下的工作.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (dataLoaded) return [self.accounts count]; return 0; }