33

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

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

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

4

6 回答 6

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");
}
于 2011-04-15T09:10:08.547 回答
13

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

  [self performSelector:@selector(doSomething) withObject:nil afterDelay:60.0f];
于 2014-05-13T14:58:54.457 回答
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
 }
}
于 2016-05-09T11:30:40.473 回答
2

斯威夫特 3:

Timer.scheduledTimer(withTimeInterval: 60, repeats: true, block: { (timer) in 
print("That took a minute")
})
于 2017-07-14T22:24:29.940 回答
0

您可以使用计划方法...

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

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

[self schedule:@selector(callFunction:) interval:60.0f];
于 2011-04-15T09:24:15.460 回答
0

斯威夫特 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")
}
于 2019-09-06T08:39:57.670 回答