2012-03-15 92 views
0

下面的函數(即dateChanged())由UIDatePickersolve觸發。我的問題是,如何從NSDate檢索字符串?

NSLog(@"Future: %@", futureDate); 

返回'null'。但是,

NSLog(@"Today: %@", today); 

工作得很好。

我知道,鑄造發件人爲的UIDatePicker,讓我解決使用問題:

futureDate = [dateFormat stringFromDate:sender.date]; 

,但我不明白爲什麼我不能投發件人爲一個NSDate。任何有識之士將不勝感激。

//- (IBAction)dateChanged:(UIDatePicker*)sender { 
    - (IBAction)dateChanged:(NSDate *)sender { 
    NSDate* todaysDate = [NSDate date]; 
    NSDateFormatter* dateFormat; 
    dateFormat=[[NSDateFormatter alloc] init]; 
    [dateFormat setDateFormat:@"MMMM d, yyyy hh:mm:ssa"]; 
    NSString * today; 
    NSString * futureDate; 
    today=[dateFormat stringFromDate:todaysDate]; 
    NSLog(@"Today: %@", today); 
    futureDate = [dateFormat stringFromDate:sender]; 
    NSLog(@"Future: %@", futureDate); 
    } 

回答

1

確定您可以將發件人轉換爲NSDate *。或者UIButton * - 或其他任何東西。然而,它並沒有改變日期選擇器實現發送UIDatePicker *作爲委託消息參數的事實,並且該投射將是無效的。最靈活的委託消息將id作爲返回參數的一種類型,但傳遞的對象始終是某個類的對象。而且,對於已鑄造類的代碼完成和警告,Objective-c鑄造僅使您的調試和開發過程更加輕鬆。

0

這需要作爲UIDatePicker而非NSDate進行處理。此外,在Interface Builder中很容易將傳入的對象從類型ID更改爲本機類型。這會使接口和實現文件中的連接正確。我偶爾會在使用UIButton等對象的自定義子類時執行此操作。

- (IBAction) dateChanged:(UIDatePicker *)sender { 
    NSDate* todaysDate = [NSDate date]; 
    NSDateFormatter* dateFormat; 
    dateFormat=[[NSDateFormatter alloc] init]; 
    [dateFormat setDateFormat:@"MMMM d, yyyy hh:mm:ssa"]; 
    NSString * today; 
    NSString * futureDate; 
    today=[dateFormat stringFromDate:todaysDate]; 
    NSLog(@"Today: %@", today); 
    futureDate = [dateFormat stringFromDate:sender.date]; 
    NSLog(@"Future: %@", futureDate); 
}