gpt4 book ai didi

swift - 错开 NSTimer

转载 作者:搜寻专家 更新时间:2023-11-01 07:34:10 25 4
gpt4 key购买 nike

我有 3 个不同的 NSTimer,我想每 0.3 秒触发一次,但我希望 3 个 NSTimer 交错排列,这样它们就不会同时触发。例如,NSTimer1 在 0.1 时触发,然后在 0.4 时触发,NSTimer2 在 0.2 时触发,然后在 0.5 时触发,NSTimer3 在 0.3 时触发,然后在 0.6 时触发,依此类推。

下面是我目前正在使用的,我不确定它们是否真的同时发射,我只是假设。任何建议将不胜感激。

var timer1 = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: Selector("updateSegment1"), userInfo: nil, repeats: true)
var timer2 = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: Selector("updateSegment2"), userInfo: nil, repeats: true)
var timer3 = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: Selector("updateSegment3"), userInfo: nil, repeats: true)

最佳答案

您可以使用 block 来完成此操作。

-(void)didMoveToView:(SKView *)view {

SKAction *wait0 = [SKAction waitForDuration:0.1];
SKAction *block0 = [SKAction runBlock:^{
// run first timer code
}];
[self runAction:[SKAction sequence:@[wait0, block0]]];

SKAction *wait1 = [SKAction waitForDuration:0.2];
SKAction *block1 = [SKAction runBlock:^{
// run second timer code
}];
[self runAction:[SKAction sequence:@[wait1, block1]]];

SKAction *wait2 = [SKAction waitForDuration:0.3];
SKAction *block2 = [SKAction runBlock:^{
// run third timer code
}];
[self runAction:[SKAction sequence:@[wait2, block2]]];

}

如果你想使用 dispatch,试试这个代码...

为您的计时器创建一个属性:

@property (nonatomic, strong) dispatch_source_t myTimer;

接下来,创建计时器:

// Get the queue to run the blocks on
dispatch_queue_t queue = dispatch_get_main_queue();

// Create a dispatch source, and make it into a timer that goes off every second
self.myTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(self.myTimer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0);

// When the timer goes off, run your code
dispatch_source_set_event_handler(self.myTimer, ^{
//code...
});

// Dispatch sources start out paused, so start the timer by resuming it
dispatch_resume(self.myTimer);

// To cancel the timer, just set the timer variable to nil:
self.myTimer = nil;

关于swift - 错开 NSTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31006331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com