切换选项卡(最初)非常慢 - 将函数移出 viewDidLoad?
在我的 iPhone 应用程序中,我使用 UITabBarController
布局了三个选项卡。第一个选项卡(在应用程序启动时加载)使用本地数据加载,并且速度非常快。
然而,第二个选项卡从网络下载 XML 文件并解析它,然后在 UITableView
中显示所有数据,在较慢的连接(EDGE、3G)上需要很长时间才能加载。而且,由于我确实在 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 - 代码被调用,但我如何确保解析的文章加载回我的表视图?
In my iPhone app, I have three tabs laid out using a UITabBarController
. The first tab (that loads on app launch) uses local data to load, and is very fast.
The second tab, though, which downloads an XML file from the web and parses it, then displays all the data in a UITableView
, takes a long time to load over slower connections (EDGE, 3G). And, since I do call my parser inside viewDidLoad
, the app won't switch to my second tab until everything is done—this means it takes a while to load the tab sometimes, and it looks like the app's locked up.
I'd rather be able to have the user switch to that tab, have the view load immediately—even if empty, and then have the data downloaded/parsed/displayed. I have the network activity spinner spinning, so at least the user can know something's happening.
Here's my current 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];
}
I found this article, which shows how to run threads in the background, but I tried implementing that code and couldn't get the background thread to load the data back into my UITableView - the code was called, but how would I make sure the parsed articles are loaded back into my table view?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事实证明,我需要在辅助线程中加载数据后重新加载 UITableView,这解决了所有问题!
这是我的辅助线程 + viewDidLoad 函数中的最终代码:
我想起了从这个答案刷新表视图: UITableView 不显示解析的数据
It turns out I needed to reload my UITableView after loading the data in a secondary thread, and that fixes everything!
Here's the final code in my secondary thread + viewDidLoad function:
I was reminded of refreshing the table view from this answer: UITableView not displaying parsed data