在iPhone中每60秒后调用一个方法

时间:2011-04-15 08:49:58

标签: iphone timer nstimer gksession

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

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

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

6 个答案:

答案 0 :(得分:94)

使用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");
}

答案 1 :(得分:13)

将NSTimer设置为scheduleWithTimeInterval后,立即调用它。 你可以使用

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

答案 2 :(得分:3)

使用以下代码:

 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
 }
}

答案 3 :(得分:2)

斯威夫特3:

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

答案 4 :(得分:0)

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

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

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

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

答案 5 :(得分:0)

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")
}