0

对不起这个问题。我必须节省点击按钮的时间

第一次,然后将时间与未来时间进行比较,如果大于或

等于我必须触发一个方法或一个警报的同时。

这是代码。

-(IBAction)checkInButtonClicked
{
    now = [NSDate date];
   [[NSUserDefaults standardUserDefaults]setObject:now forKey:@"theFutureDate"];

    NSTimeInterval timeToAddInDays = 60 * 60 * 24;
    theFutureDate = [now dateByAddingTimeInterval:timeToAddInDays];

    switch ([now compare:theFutureDate]){
    case NSOrderedAscending:{
    NSLog(@"NSOrderedAscending");

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:
    [NSString stringWithFormat:@"Oops! The Check In will activate after 24Hrs"] 
    delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil ];
    [alert show];
    }
    break;
    case NSOrderedSame:{
    NSLog(@"NSOrderedSame");
    [self insertPoints];
   }
    break;
    case NSOrderedDescending:{
    NSLog(@"NSOrderedDescending");
   }
    break;
   }
  }

但是这段代码不能完全正常工作。谁能帮帮我。

提前致谢。

4

1 回答 1

0

问题是您总是now在与未来的日期进行比较。这种比较总是有相同的结果。

如果我理解正确,您想要完全相反。您必须now与用户第一次单击该按钮的时间进行比较。因此,您NSUserDefaults仅在第一次设置日期并在第二次和后续时间进行比较。

- (IBAction)checkInButtonClicked {     
    NSDate *now = [NSDate date];
    NSDate *firstTimeClicked = [[NSUserDefaults standardUserDefaults] objectForKey:@"firstTimeClicked"];
    if (firstTimeClicked) {
        /* this is at least the second time the button has been clicked */        
        NSTimeInterval delta = [now timeIntervalSinceDate:firstTimeClicked];
        if (delta > 24 * 3600) {
            /* button clicked > 1 day ago */
        } else {
            /* button clicked <= 1 day ago */
        }
    } else {
        /* not present in NSUserDefaults, it's first click */
        [[NSUserDefaults standardUserDefaults] setObject:now forKey:@"firstTimeClicked"];   
    }
}
于 2012-09-18T09:00:34.570 回答