【问题标题】:How to use NSTimer with data from NSURL pass to NSXMLParser display in TableView如何使用 NSTimer 与从 NSURL 传递到 NSXMLParser 的数据在 TableView 中显示
【发布时间】:2012-08-13 15:25:58
【问题描述】:

如何使用 NSTimer 将数据从 NSURL 传递到 NSXMLParser 在 TableView 中显示

我有通过 PHP gen' 从 Web 服务器到 XML 的应用程序显示数据

在我的 xcode 中,我使用 NSURL 连接到 PHP 文件(在 Web 服务器中) 并使用 NSXMLParser 读取 XML 数据将值放入数组 并最终显示在 TableView 上

我想查看 TableView 中的数据实时更新或每 x 次更新一次

我想我可以使用 NSTimer,但我不知道我该怎么做 我可以将 NSTimer 放到 xcode 中的代码中

【问题讨论】:

    标签: tableview nstimer nsxmlparser nsurl


    【解决方案1】:

    简而言之,类似于:

    // Schedule a timer repeating every 2 seconds
    [NSTimer scheduledTimerWithTimeInterval:2.0
                                     target:self.tableView
                                   selector:@selector(reloadData)
                                   userInfo:nil
                                    repeats:YES];
    

    加长版:

    您需要从计时器调用 -doParse,获取数据,进行解析,然后重新加载数据。

    为了不阻塞主线程,您必须NOT从主线程调用[[NSXMLParser alloc] initWithContentsOfURL:theURL]

    改为:

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
          NSXMLParser *nsXmlParser = [[NSXMLParser alloc] initWithContentsOfURL:theURL];
          ...
          // finish parsing
          dispatch_async(dispatch_get_main_queue(), ^{
              [tableView reloadData];
          });
    });
    

    并使用来自 -viewDidLoad 的 NSTimer 调用 -doParse

    [NSTimer scheduledTimerWithTimeInterval:2.0
                                     target:self
                                   selector:@selector(doParse)
                                   userInfo:nil
                                    repeats:YES];
    

    进一步阅读: WWDC 2012 Session 211 - 在 iOS 上构建并发用户界面。

    【讨论】:

    • 在我的代码vasuta.com/ios/MyLoxFile.zip ...文件“MyLoxFileTVContoller.m”中,我将第 36 行到第 79 行移到 dispatch_async 中,对吗? ...我将 dispatch_async 放在我的项目中的什么位置?
    • 你必须至少取消注释两个[self.tableView reloadData];之一
    • 如果我使用 [self.tableView reloadData]; tableview 它没有显示在我的视图中
    猜你喜欢
    • 2016-01-25
    • 2023-04-09
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多