我正在构建一个应用程序,我需要堆叠到两个定时事件(一个在另一个内)。我有一个计时器,它将每隔10秒调用一次Web服务并获取新数据。在Web服务调用之间,我将为我收到的每个对象设置10秒钟的动画(以弥合差距并创建'实时'感觉)。
我从网络服务收到的数据量会有所不同,因此我的动画计时器需要改变,以便在10秒内将动画空间分开。
我正在尝试更改重复的NSTimer的timeInterval,但是在下一个数据集进入时无法更改时间间隔。
timerDelay = 9.8/([timerAdditions count]-1);
if (!delayTimer) {
delayTimer =[NSTimer scheduledTimerWithTimeInterval:timerDelay target:self selector:@selector(delayMethod) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:delayTimer forMode:NSRunLoopCommonModes];
} else {
NSTimeInterval timeInMiliseconds = timerDelay;
NSDate *myDate =[NSDate dateWithTimeIntervalSinceNow:timeInMiliseconds];
delayTimer.fireDate = myDate;
}
答案 0 :(得分:1)
我发现协调两个定时器的最好方法是只有一个定时器,用作脉冲。我会做这样的事情:
// keep state on when the next fetch should happen
@property(strong,nonatomic) NSDate *fetchTime;
// keep state on how much animation to do per tick
@property(assign,nonatomic) NSInteger mapPointsPerFrame;
// run a single timer at the highest frame-rate you'll need
NSTimer *timer =[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
- (void)timerFired:(NSTimer *)timer {
// is it time to do a fetch?
NSDate *now = [NSDate date];
if ([self.fetchTime laterDate:now] == self.fetchTime) {
// call a method to start a new fetch
self.fetchTime = [NSDate dateWithTimeInterval:10 sinceDate:now];
}
// either way, do animations if they are needed
NSInteger mapPoints = self.mapPointsPerFrame;
while (self.mapPointsToAnimate.count && mapPoints) {
// call a method to add a map point
mapPoints--;
}
}
唯一要做的就是设置self.mapPointsPerFrame。每次获取后执行此操作。如果你的帧间隔是0.5秒而你每10秒获取一次,那么它的等式如下:
// just fetched N things and added N objects to self.mapPointsToAnimate
// try to animate them all by the next fetch
self.mapPointsPerFrame = (self.mapPointsToAnimate.count / 20) + 0.5; // 0.5 to round