2012-07-11 45 views
1

我是新來的iPhone開發者,加入月月NewDate

我,我想根據頻率增加1 month3 month6 month是自定義的日期做出了一個custom date

我想添加一個月,直到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];

任何幫助將BW讚賞。

回答

3

再次向temp提供值,則不需要再次提供NSDate對象類型。這裏ü已經擁有的NSDate *溫度,那麼爲什麼[Rü再次使用相同名稱的NSDate對象

temp= [[NSCalendar currentCalendar] dateByAddingComponents:newComponents toDate:temp options:0] 
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