-1

嗨,我正在尝试在特定日期做某事,目前我只是记录一些随机的东西,但日志在应用程序启动时直接出现,而不是在我设置的日期。这是我的代码。

-(void)theMagicDate{

    NSCalendar *nextCal = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *nextComp = [nextCal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit fromDate:[NSDate date]];

    [nextComp setYear:2013];
    [nextComp setMonth:3];
    [nextComp setDay:26];
    [nextComp setHour:10];
    [nextComp setMinute:05];

    UIDatePicker *nextDay = [[UIDatePicker alloc]init];
    [nextDay setDate:[nextCal dateFromComponents:nextComp]];

    if(nextDay.date){
        NSLog(@"Doing the stuff on the date");
    }
}

我从 viewDidLoad 调用这个函数

4

2 回答 2

3

好吧,您正在做出一些错误的假设:

首先if(nextDay.date){永远是真的。因为它只会检查是否有任何东西分配给财产日期。由于您为该属性分配了日期,因此它将是正确的。

其次,这UIDatePicker是一个允许用户选择日期的用户界面 (UI) 组件。如果您想检查您使用组件创建的日期是否已粘贴、现在或将来,您将不得不使用NSDate.

像这样:

-(void)theMagicDate{

NSCalendar *nextCal = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *nextComp = [nextCal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit fromDate:[NSDate date]];

[nextComp setYear:2013];
[nextComp setMonth:3];
[nextComp setDay:26];
[nextComp setHour:10];
[nextComp setMinute:05];

NSDate *dateToCheck = [nextCal dateFromComponents:nextComp];
NSDate *now = [NSDate date];


switch ([now compare:dateToCheck]) {
    case NSOrderedAscending:
        NSLog(@"Date in the future");
        break;

    case NSOrderedDescending:
        NSLog(@"Date in the past");
        break;

    case NSOrderedSame:
        NSLog(@"Date is now");
        break;
}


}
于 2013-03-26T09:08:22.530 回答
0
if(nextDay.date){
    NSLog(@"Doing the stuff on the date");
}

永远是真的。

您需要将当前日期与您从选择器或任何地方选择的日期进行比较。您需要将未来日期保存在 userdefaults 或 plist 等中。在 MagicDate 方法中读取它并比较两个日期,然后进入NSLog(@"Doing the stuff on the date");

-(void)theMagicDate{

    NSCalendar *nextCal = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *nextComp = [nextCal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit fromDate:[NSDate date]];

    [nextComp setYear:2013];
    [nextComp setMonth:3];
    [nextComp setDay:26];
    [nextComp setHour:10];
    [nextComp setMinute:05];

    UIDatePicker *nextDay = [[UIDatePicker alloc]init];
    [nextDay setDate:[nextCal dateFromComponents:nextComp]];


     //read from plist etc
     NSDate *readDate=...


    if( [readDate compare:nextDay.date]==NSOrderedSame){
        NSLog(@"Doing the stuff on the date");
    }
}
于 2013-03-26T09:08:09.663 回答