1

我是 iPhone 开发者的新手,

custom date在我想添加的自定义日期或1 month根据频率制作了一个。3 month6 month

我想添加月份,直到 newDate 小于今天的日期。

这是我的代码片段,

 while ([today compare:temp] == NSOrderedDescending) 
    {        
        NSLog(@"inside----- today=%@,temp=%@",today,temp);

        //add to dates
        NSDateComponents *newComponents= [[NSDateComponents alloc] init];

        if([FrequencySelText isEqualToString:@"Monthly"]){

            [newComponents setMonth:1];
        }
        if([FrequencySelText isEqualToString:@"Quarterly"]){

            [newComponents setMonth:3];
        }
        if([FrequencySelText isEqualToString:@"Half - Yearly"]){

            [newComponents setMonth:6];
        }
        if([FrequencySelText isEqualToString:@"Yearly"]){

            [newComponents setMonth:12];
        }

        // get a new date by adding components
        NSDate* temp= [[NSCalendar currentCalendar] dateByAddingComponents:newComponents toDate:temp options:0];

        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"dd/MM/yyyy"];

        NSString *newDate = [formatter stringFromDate:temp];
        NSLog(@"new date=%@",newDate);
}

我的日志显示: inside----- today=2012-07-11 14:41:27 +0000,temp=2012-04-12 03:00:00 +0000

我正在Exc_bad_access这条线上,NSDate* temp= [[NSCalendar currentCalendar] dateByAddingComponents:newComponents toDate:temp options:0];

任何帮助将不胜感激。

4

2 回答 2

3

再次为 temp 提供值,则无需再次提供 NSDate 对象类型。在这里你已经有了 NSDate *temp 那么为什么 ru 再次为 NSDate 对象使用相同的名称

 temp= [[NSCalendar currentCalendar] dateByAddingComponents:newComponents toDate:temp options:0] 
于 2012-07-11T06:58:49.007 回答
0

也许试试这个:

NSDateComponents *dateComponents = [[[NSDateComponents alloc] init] autorelease];
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];

[dateComponents setMonth:1]; // Sample Add   

NSDate *tempDate = [gregorian dateByAddingComponents:dateComponents toDate: temp options:0];
NSString *strTempDate = [dateFormat stringFromDate:tempDate];

// New Date on strTempDate
于 2012-07-11T08:43:00.227 回答