我正在开发一款可以每秒更新生物数量的游戏。但是,即使用户进入后台状态,我也希望游戏继续更新。为了做到这一点,我想使用自用户进入后台以来的时间。
我正在使用app委托将时间存储在NSUserDefaults中,并带有函数
- (void)applicationWillResignActive:(UIApplication *)application {
//When application is going into background
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"backgroundTime"];
- (void)applicationWillEnterForeground:(UIApplication *)application {
//When application comes back from background state
NSDate *prevDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"backgroundTime"];
NSDate *currDate = [NSDate date];
NSTimeInterval interval = [currDate timeIntervalSinceDate:prevDate];
NSLog(@"%f",interval);
}
在我的视图控制器中,我使用此方法根据时间更新计数。如何实现一个功能来正确计算后台时间?
- (void)viewDidLoad {
[super viewDidLoad];
[self initialize];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(adjustCountsBasedOnTime) userInfo:nil repeats:YES];
}
-(void)adjustCountsBasedOnTime{
NSDecimal addition;
NSDecimal mutationIncrease = [[NSDecimalNumber decimalNumberWithString:@"1"]decimalValue];
NSDecimalAdd(&_mutationNumber, &_mutationNumber, &mutationIncrease, NSRoundBankers);
NSDecimalMultiply(&addition, &_tierOneCreatureNumber, &_tierOneProductionRate, NSRoundBankers);
NSDecimalAdd(&_sugarNumber, &addition, &_sugarNumber, NSRoundBankers);
NSDecimalMultiply(&addition, &_tierTwoCreatureNumber, &_tierTwoProductionRate, NSRoundBankers);
NSDecimalAdd(&_tierOneCreatureNumber, &_tierOneCreatureNumber, &addition, NSRoundBankers);
NSDecimalMultiply(&addition, &_tierThreeCreatureNumber, &_tierThreeProductionRate, NSRoundBankers);
NSDecimalAdd(&_tierTwoCreatureNumber, &_tierTwoCreatureNumber, &addition, NSRoundBankers);
NSDecimalMultiply(&addition, &_tierFourCreatureNumber, &_tierFourProductionRate, NSRoundBankers);
NSDecimalAdd(&_tierThreeCreatureNumber, &_tierThreeCreatureNumber, &addition, NSRoundBankers);
NSDecimalMultiply(&addition, &_tierFiveCreatureNumber, &_tierFiveProductionRate, NSRoundBankers);
NSDecimalAdd(&_tierFourCreatureNumber, &_tierFourCreatureNumber, &addition, NSRoundBankers);
NSDecimalMultiply(&addition, &_tierSixCreatureNumber, &_tierSixProductionRate, NSRoundBankers);
NSDecimalAdd(&_tierFiveCreatureNumber, &_tierFiveCreatureNumber, &addition, NSRoundBankers);
NSDecimalMultiply(&addition, &_tierSevenCreatureNumber, &_tierSevenProductionRate, NSRoundBankers);
NSDecimalAdd(&_tierSixCreatureNumber, &_tierSixCreatureNumber, &addition, NSRoundBankers);
NSDecimalMultiply(&addition, &_tierEightCreatureNumber, &_tierEightProductionRate, NSRoundBankers);
NSDecimalAdd(&_tierSevenCreatureNumber, &_tierSevenCreatureNumber, &addition, NSRoundBankers);
NSDecimalMultiply(&addition, &_tierNineCreatureNumber, &_tierNineProductionRate, NSRoundBankers);
NSDecimalAdd(&_tierEightCreatureNumber, &_tierEightCreatureNumber, &addition, NSRoundBankers);
}
答案 0 :(得分:0)
这个最简单的想法是在将应用程序带到前台后执行adjustCountsBasedOnTime
,interval
次。
使用新方法adjustCountsBasedOnDuration
进行数学运算并根据持续时间确定新计数应该更好。