【问题标题】:Continuously check for data (method) iOS持续检查数据(方法) iOS
【发布时间】:2012-07-24 17:49:05
【问题描述】:

有没有什么方法(比如——viewDidLoad)可以连续执行一部分代码?我需要能够持续检查远程服务器上的值。

【问题讨论】:

  • ...NSTimer 在单例类中? :D

标签: ios cocoa-touch continuous


【解决方案1】:

这样做的方法是设置一个 NSTimer。

-(void)startCheckingValue
{
    mainTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(checkValue:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:mainTimer forMode:NSDefaultRunLoopMode];
}

-(void)checkValue:(NSTimer *)mainTimer
{
    //Placeholder Function, this is where you write the code to check your value on the remote server
}

timerWithTimeInterval 函数是您感兴趣的函数,正如您在上面看到的,您需要传递它的主要内容是它将执行您传递它的选择器的函数的时间间隔。时间间隔以秒为单位,因此目前设置为每秒检查一次,这可能太快了。

【讨论】:

  • 有更有效的方法吗?此方法(设置为 0.01 秒)在 3 台 iPad 上进行了 30 分钟的测试,在 Parse 上生成了 230,526 个 API 请求。我需要类似于计时器设置为 0.01 秒的效率。
【解决方案2】:

使用 NSTimer 每 x 秒执行一次相同的代码块。但是,我认为这不是您想要的,因为它会给服务器带来很多额外的负载并且您可能会被禁止,所以可能有更好的方法。

apple's page on NSTimer use

【讨论】:

    【解决方案3】:

    你需要使用 NSTimer 来做这个:

    在您的界面中声明一个NSTimer 对象,例如:

    NSTimer *timer;
    

    在您的 .m viewDidLoad 方法中添加以下行。

    timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
    

    timerFireMethod 方法中,您需要进行服务器调用和其他工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-09
      • 1970-01-01
      • 1970-01-01
      • 2012-01-31
      • 2022-06-11
      • 2012-08-15
      • 2013-11-27
      • 2021-01-20
      相关资源
      最近更新 更多