2012-03-09 51 views
11

indexNumber.row是一個日期,如2012-03-09 23:00:00 +0000。我已經嘗試了幾種不同的方法,讓我的日期進入NSDate,但我一直得到標題錯誤。將字符串轉換爲NSDate問題:[__NSDate長度]無法識別選中

NSString *inputString = [self.measurements objectAtIndex:indexNumber.row]; 

// Convert string to date object 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd"]; 
NSDate *date = [dateFormatter dateFromString:inputString ]; 
NSLog(@"date format is: %@", date); 

任何想法,爲什麼我收到以下錯誤:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDate length]: unrecognized selector sent to instance 0x6ca0c60'

+0

你會得到什麼樣的錯誤,你能更具體一點嗎? – Emil 2012-03-09 16:18:59

回答

28

你,因爲你正在傳遞一個NSDate對象dateFromString:得到這個錯誤。

添加NSLog,你會看到:

NSString *inputString = [self.measurements objectAtIndex:indexNumber.row]; 
if ([inputString isKindOfClass:[NSDate class]]) { 
    NSLog(@"inputString is of type NSDate"); 
} 

而且,這裏是如何重現你的錯誤:

NSString *inputString = [NSDate date]; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
NSDate *date = [dateFormatter dateFromString:inputString]; 

這意味着數組self.measurements包含NSDate對象,而不是NSString對象。


當您更正當前問題時,可能會遇到新問題,因爲您沒有使用正確的日期格式。要解析類型的日期字符串:2012-03-09 23:00:00 +0000你應該使用下面的日期格式:

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zz"]; 
+1

我試過幾個不同的setDateformats。我得到了與上述格式相同的錯誤:「終止應用程序由於未捕獲異常'NSInvalidArgumentException',原因:' - [__ NSDate長度]:無法識別的選擇發送到實例0x6ca0c60'」 – BamBamBeano 2012-03-09 16:25:50

+0

設置字符串並獲得「日期後添加NSLog格式是:2012-03-09 09:36:53 +0000「 – BamBamBeano 2012-03-09 16:28:46

+0

釘了它。運行你的if後,它實際上是一個NSDate,不需要轉換。謝謝sch。 – BamBamBeano 2012-03-09 18:31:32

0

要麼是作爲SCH建議,或者如果你不需要多長時間,你可以截斷字符串你提供給你的dateFormatter。例如。像這樣:

NSDate *date = [dateFormatter dateFromString:[inputString substringToIndex:9]]; 

凡是一個索引,最多要採取串的一大塊。

+0

這不會解決他的問題。如果問題是日期格式化,他會得到一個「無」日期,而不是他提到的錯誤。 – sch 2012-03-09 16:37:38

+0

如果問題出在日期格式和給定字符串格式之間的區別 - 它**將解決問題。如果字符串是* nil *,那麼當然它不會給你任何東西,以及你的建議。 – makaron 2012-03-09 16:49:29