嗨, friend 们,我需要每 30 分钟增加一次生命的倒数计时器。所以我创建了一个倒数计时器,但它只在那个调用上运行。在这里我需要全局运行的定时器。如果在背景中应用或终止任何机构帮助我。
这是我的代码
int hours, minutes, seconds;
NSTimer *timer;
- (void)updateCounter:(NSTimer *)theTimer {
if(secondsLeft > 0 ){
secondsLeft -- ;
// hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
// myCounterLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
[self removeChild:Liveslable];
Liveslable=[CCLabelTTF labelWithString:[NSString stringWithFormat:@"lives left in %02d:%02d minuts",minutes, seconds] fontName:@"ArialMT" fontSize:25];
Liveslable.position=ccp(winSize.width/2, winSize.height/2-140);
[self addChild:Liveslable];
}
else{
secondsLeft = 1800;
}
}
-(void)countdownTimer{
secondsLeft = hours = minutes = seconds = 0;
if([timer isValid])
{
[timer release];
}
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];
[pool release];
}
最佳答案
在这种情况下使用NSTimer
是不合适的。您不能在后台执行代码,这是有充分理由的(想象一下如果用户退出进程或关闭设备)。相反,您应该考虑存储赋予生命的时间戳,然后计算赋予下一次生命的时间戳。
您可以像这样将时间保存到 NSUserDefaults
:
float timeStamp = [[NSDate date] timeIntervalSince1970] * 1000; // Milliseconds
[[NSUserDefaults standardUserDefaults] setFloat:timeStamp forKey:@"lastTimeStamp"];
然后像这样检索以前的时间戳:
float lastTime = [[NSUserDefaults standardUserDefaults] floatForKey:@"lastTimeStamp"];
每当用户打开应用程序时,您都应该执行计算并相应地赋予生命。这可以在 AppDelegate.m
applicationWillEnterForeground:
中完成
您可以使用 NSTimer
检查下一个时间戳是否与应用程序运行时的 NSDate
时间匹配。
关于ios - 我如何在 cocos2d 中创建 30 分钟的倒数计时器,就像 candy crush lives 一样。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24360895/