2012-07-10 94 views
2

我是新來的iPhone開發者,比較兩個NSDates在iPhone

我想比較兩個日期,第一次約會將來自數據庫讓說,newDate和第二個是今天的日期,

如果今天是更大然後newDate然後我想顯示警報。

這裏是我的代碼片段,

NSString *newDate = [formatter stringFromDate:st]; 
NSDate *today=[[NSDate alloc]init]; 

if ([today compare:newDate] == NSOrderedDescending) 
{ 
    NSLog(@"today is later than newDate");   
} 
else if ([today compare:newDate] == NSOrderedAscending) 
{ 
    NSLog(@"today is earlier than newDate");   
} 
else 
{ 
    NSLog(@"dates are the same");   
} 

,但它崩潰,並且在編譯這也說明我在這裏警告[today compare:newDate]

任何幫助將不勝感激。

+0

這會幫助你: http://stackoverflow.com/questions/5965044/how-to-compare-two-nsdates-which-is-more-recent – 2012-07-10 12:02:20

+0

什麼是警告說,對'[今天比較:newDate]'?也許這個警告應該給你一個線索? – 2012-07-10 12:07:15

回答

6

問題是,您正在比較字符串和日期。如果你看newDate,你會看到它的NSString而不是NSDate。如果您在NSDate上使用compare:方法,則兩個對象都必須是NSDate's。看你的代碼,它看起來像st是對應的NSDatenewDate(雖然你的命名似乎有點奇怪),嘗試用today它,而不是newDate

-1

您正在嘗試比較日期對象與字符串。你需要比較日期對象。

[today compare:newDate] == NSOrderedDescending) 

newDate應該是一個NSDate實例。我已經完成了這個工作。