Xcode:在特定日期做点什么

时间:2013-03-26 09:04:26

标签: objective-c xcode date 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];

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

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

我从viewDidLoad

调用此函数

2 个答案:

答案 0 :(得分: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;
}


}

答案 1 :(得分:0)

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

总是如此。

您需要将当前日期与您从选择器或任何地方选择的日期进行比较。您需要将未来日期保存在userdefaults或plist等中。在theMagicDate方法中读取它并比较两个日期,然后进入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");
    }
}
相关问题