2013-07-01 89 views
0

我想將NSString轉換爲日期,添加一天到它,然後轉換回字符串。轉換和從NSDate導致崩潰

到目前爲止我的代碼是這樣的:

//convert curDate (from @property declaration) to NSDate 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"dd-MM-yyyy"]; 
NSDate *dateFromString = [[NSDate alloc] init]; 
dateFromString = [dateFormatter dateFromString:curDate]; 

//add a day 
dateFromString = [dateFromString dateByAddingTimeInterval:60*60*24*1]; 

//convert back to string (for use in URL string concatenation) 
NSString *dateDisplay = [dateFormatter stringFromDate:dateFromString]; 

//set curDate to new date 
curDate = dateDisplay; 

它崩潰的堆棧在:

0x117f09b: movl 8(%edx), %edi 

(不知道這是非常有用的)。

有誰能說這是爲什麼?

謝謝!

+0

代碼放在'@ try''@ catch'塊,並打印出異常。 – pbibergal

+3

如果爲拋出的任何異常添加符號斷點,則更好。但是我試過你的代碼,它不會拋出任何異常。 –

+1

可能日期格式與字符串不匹配,而'dateFromString'爲'nil'。 - 在調試器中單步調試(並檢查變量)可能非常有用! –

回答

-4
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 

[dateFormatter setDateFormat:@"dd-MM-yyyy"]; 

//add a day 

NSDate *dateFromString = [[NSDate date] dateByAddingTimeInterval:60*60*24*1]; 

//convert back to string (for use in URL string concatenation) 

NSString *dateDisplay = [dateFormatter stringFromDate:dateFromString]; 
+2

您是否更改過任何* OP的代碼?你似乎正在做同樣的事情(包括不正確的日期添加和未使用的日期對象,如果ARC沒有保存你,它將成爲內存泄漏)。 –

+0

dateFromString = [dateFromString dateByAddingTimeInterval:60 * 60 * 24 * 1];這條線只會崩潰。我已經改變了這一行代碼,在當前日期添加時間[NSDate date] dateFromString = [[NSDate date] dateByAddingTimeInterval:60 * 60 * 24 * 1]; – karthika

+0

然後,指出這一變化並解釋其重要性會非常有幫助。 –

2

你應該使用NSDateComponents

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"dd-MM-yyyy"]; 
NSDate *dateFromString = [dateFormatter dateFromString:self.curDate]; 

// Create components 
NSDateComponents *dateComponents = [[NSDateComponents alloc] init]; 
dateComponents.day = 1; 

// Get the calendar to add the components to a date 
NSCalendar *calendar = [NSCalendar currentCalendar]; 
NSDate *incrementedDate = [calendar dateByAddingComponents:dateComponents toDate:dateFromString options:0]; 

NSString *dateDisplay = [dateFormatter stringFromDate:incrementedDate]; 

//set curDate to new date 
curDate = dateDisplay; 
+1

dateComponent.day應該是dateComponents.day。 –