【问题标题】:calling a method after each 60 seconds in iPhone在 iPhone 中每 60 秒调用一次方法
【发布时间】:2011-08-06 04:08:40
【问题描述】:

我创建了一个 GKSession,当它的对象被创建时,它开始搜索设备的可用性,因为

 - (void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state {

我想每隔 60 秒调用一次这个方法,我该怎么办?

【问题讨论】:

标签: iphone timer nstimer gksession


【解决方案1】:

使用NSTimer

NSTimer* myTimer = [NSTimer scheduledTimerWithTimeInterval: 60.0 target: self
                                   selector: @selector(callAfterSixtySecond:) userInfo: nil repeats: YES];

每隔 60.0 秒,iOS 会调用下面的函数

-(void) callAfterSixtySecond:(NSTimer*) t 
{
    NSLog(@"red");
}

【讨论】:

  • 但这是委托方法,每当状态改变时调用,例如从可用到不可用,
  • @Jhaliya:它是否每次都有效,即如果我在应用程序委托中实现这个 NSTimer,我希望无论我处于何种视图控制器,无论应用程序状态如何,无论是在前台、后台还是被杀。
【解决方案2】:

您可以使用调度方法...

-(void) callFunction:(CCTime)dt 
{
    NSLog(@"Calling...");
}

你可以使用这个来调用上面的函数...

[self schedule:@selector(callFunction:) interval:60.0f];

【讨论】:

  • 是的..您可以随时取消计划此方法。
【解决方案3】:

一旦将 NSTimer 设置为 scheduleWithTimeInterval,它就会立即调用它。 你可以使用

  [self performSelector:@selector(doSomething) withObject:nil afterDelay:60.0f];

【讨论】:

    【解决方案4】:

    使用以下代码:

     NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval: 60.0 target: self
                                   selector: @selector(timerFired:) userInfo: nil repeats: YES];
    
     - (void)timerFired:(NSTimer*)theTimer{
     if(condition){
           [theTimer isValid]; //recall the NSTimer
           //implement your methods
      }else{
          [theTimer invalidate]; //stop the NSTimer
     }
    }
    

    【讨论】:

      【解决方案5】:

      斯威夫特 3:

      Timer.scheduledTimer(withTimeInterval: 60, repeats: true, block: { (timer) in 
      print("That took a minute")
      })
      

      【讨论】:

        【解决方案6】:

        Swift 5.0

        var timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
        
        @objc func updateTimer() {
           print("1 min passed")
        }
        

        【讨论】:

          猜你喜欢
          • 2011-03-09
          • 1970-01-01
          • 1970-01-01
          • 2012-01-09
          • 1970-01-01
          • 2019-02-01
          • 2012-10-08
          • 1970-01-01
          相关资源
          最近更新 更多