0

在我的 iPhone 应用程序中,我使用UITabBarController. 第一个选项卡(在应用启动时加载)使用本地数据进行加载,而且速度非常快。

但是,第二个选项卡从 Web 下载 XML 文件并对其进行解析,然后在 a 中显示所有数据,UITableView在较慢的连接(EDGE、3G)上加载需要很长时间。而且,由于我确实调用了我的解析器 inside viewDidLoad,所以在一切完成之前,应用程序不会切换到我的第二个选项卡——这意味着有时加载选项卡需要一段时间,而且看起来应用程序被锁定了。

我宁愿让用户切换到该选项卡,立即加载视图——即使是空的,然后下载/解析/显示数据。我让网络活动微调器在旋转,所以至少用户可以知道正在发生的事情。

这是我目前的viewDidLoad

// Load in the latest stories when the app is launched.
- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"Loading news view");

    articles = [[NSMutableArray alloc] init];

    NSURL *url = [NSURL URLWithString:@"http://example.com/mobile-app/latest-news.xml"];
    NSLog(@"About to parse URL: %@", url);
    parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
    parser.delegate = self;
    [parser parse];
}

我找到了这篇文章,它展示了如何在后台运行线程,但我尝试实现该代码并且无法让后台线程将数据加载回我的 UITableView - 代码被调用,但我将如何确保解析的文章被加载回我的表格视图?

4

1 回答 1

3

事实证明,在辅助线程中加载数据后,我需要重新加载我的 UITableView,这可以解决所有问题!

这是我的辅助线程 + viewDidLoad 函数中的最终代码:

-(void)initilizeNewsViewWithData {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // Start the network activity spinner in the top status bar.
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    articles = [[NSMutableArray alloc] init];
    NSURL *url = [NSURL URLWithString:@"http://example.com/mobile-app/latest-news.xml"];
    parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
    parser.delegate = self;
    [parser parse];
    [tblLatestNews reloadData]; // Need to refresh the table after we fill up the array again.

    [pool release];
}

// Load in the latest news stories in a secondary thread.
- (void)viewDidLoad {
    [super viewDidLoad];

    [self performSelectorInBackground:@selector(initilizeNewsViewWithData) withObject:nil];
}

I was reminded of refreshing the table view from this answer: UITableView not displaying parsed data

于 2011-02-11T01:07:48.657 回答