我创建了一个 GKSession 并创建了它的对象,它开始搜索设备的可用性,如
- (void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state {
我想在每 60 秒后调用这个方法,我该怎么办?
采用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");
}
一旦您将 NSTimer 设置为 scheduleWithTimeInterval ,它就会立即调用它。您可以使用
[self performSelector:@selector(doSomething) withObject:nil afterDelay:60.0f];
使用以下代码:
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:
Timer.scheduledTimer(withTimeInterval: 60, repeats: true, block: { (timer) in
print("That took a minute")
})
您可以使用计划方法...
-(void) callFunction:(CCTime)dt
{
NSLog(@"Calling...");
}
你可以使用这个来调用上面的函数...
[self schedule:@selector(callFunction:) interval:60.0f];
斯威夫特 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")
}