Reputation: 1469
The function below (i.e. dateChanged()) is triggered by a UIDatePickersolve . My problem is that
NSLog(@"Future: %@", futureDate);
returns 'null'. However,
NSLog(@"Today: %@", today);
works just fine.
I know that casting sender as a UIDatePicker, allows me to solve the problem using:
futureDate = [dateFormat stringFromDate:sender.date];
but I cannot understand why I cannot cast sender as an NSDate. Any insight would be much appreciated.
//- (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);
}
Upvotes: 0
Views: 71
Reputation: 14427
That would need to be casted as a UIDatePicker not NSDate. Also, it is easy to change the passed in object from type id to the native type in Interface Builder. This makes the connection properly in both the interface and implementation files. I do this occasionally when using custom subclasses of objects like UIButtons and such.
- (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);
}
Upvotes: 0
Reputation: 8944
Sure you can cast sender to be NSDate*. Or UIButton* - or whatever else. However it does't change the fact that date picker implementation sends an UIDatePicker* as a parameter of delegate message and the casting will be invalid. The most flexible delegate messages have id as a type of returned parameter, but the object passed is always an object of a certain class. And the Objective-c casting only makes your debugging and dev process easier with code completion and warnings for the casted class.
Upvotes: 1