抱歉,如果标题有点草率或令人困惑,我将尝试更详细地说明。
我的应用程序中有一个功能,允许用户每天仅使用10次。下面的代码处理每天的计数,这实际上运行良好,只是用户在调用新循环之前始终必须按两次。
我认为这与fabs
函数有关,或者用户必须在新循环上按两次的原因可能是什么?
-(void)dailyCount:(id)sender{
NSString *kFirstLaunchDateKey = @"tenPerDay";
NSDate *firstLaunchDate = [[NSUserDefaults standardUserDefaults] objectForKey:kFirstLaunchDateKey];
NSInteger count = [[NSUserDefaults standardUserDefaults] integerForKey:@"perDay"];
if (!firstLaunchDate) {
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:kFirstLaunchDateKey];
[[NSUserDefaults standardUserDefaults] setInteger:count+1 forKey:@"perDay"];
return;
}
NSTimeInterval diff = fabs([firstLaunchDate timeIntervalSinceNow]);
if (diff > 60 * 60 * 24 * 1) {
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"tenPerDay"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"perDay"];
}else{
if (count % 11 == 0) {
[UIAlertView showWithTitle:@"Daily Limit Exceeded"
message:@"Sorry, you can use this option only 10 times per day."
cancelButtonTitle:@"Ok"
otherButtonTitles:nil
tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
if (buttonIndex == [alertView cancelButtonIndex]) {
}
}];
}else {
// do something here... (Have to press twice on a new loop before it's getting called)
[[NSUserDefaults standardUserDefaults] setInteger:count+1 forKey:@"perDay"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
}
最佳答案
-(void)dailyCount:(id)sender{
NSString *kFirstLaunchDateKey = @"tenPerDay";
NSDate *firstLaunchDate = [[NSUserDefaults standardUserDefaults] objectForKey:kFirstLaunchDateKey];
if (!firstLaunchDate) {
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:kFirstLaunchDateKey];
[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"perDay"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self counterNew];
return;
}
NSTimeInterval diff = fabs([firstLaunchDate timeIntervalSinceNow]);
if (diff > 60 * 60 * 24 * 1) {
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"tenPerDay"];
[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"perDay"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self counterNew];
}else{
[self counterNew];
}
}
-(void)counterNew{
NSInteger count = [[NSUserDefaults standardUserDefaults] integerForKey:@"perDay"];
if (count > 10) {
[UIAlertView showWithTitle:@"Daily Limit Exceeded"
message:@"Sorry, you can use this option only 10 times per day."
cancelButtonTitle:@"Ok"
otherButtonTitles:nil
tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
if (buttonIndex == [alertView cancelButtonIndex]) {
}
}];
}else {
//Do something here...
[[NSUserDefaults standardUserDefaults] setInteger:count+1 forKey:@"perDay"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}