ios – 何时在UITableViewController中加载数据?

我目前正在UITableViewController的viewDidLoad方法中加载来自 JSON服务的数据.问题是数据需要时间来检索和解析,视图需要时间来创建.
加载此数据的最佳位置在哪里?我假设在创建视图后有一个钩子在某处加载数据.通过这样做,我将能够在最终视图中使用一些UIActivityIndi​​catorView.
谢谢

解决方法

最后这里有一个基于注释的解决方案:在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;
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...