Macness
Macness

Reputation: 1226

UIDatePicker and date not storing properly

I have an IBAction method tied to a UIToolbarButton that runs the following code.

The UIDatePicker is setup only to show the time to the user. Therefore, the picker randomly chooses the date: sometimes the date is today, sometimes the date is tomorrow. I want the picker to always choose the time selected (but always in the future). e.g. If the user picks 6:00AM at 10:00PM on Jan 1st, I want the date to store 6:00 AM on Jan 2nd.

The following if should do that, however 50% of the time NSLog returns one answer and 50% of the time it returns the other.

if (self.picker.date >= [NSDate dateWithTimeIntervalSinceNow:0]) {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDate *pickerdate = self.picker.date;
    [defaults setObject:pickerdate forKey:@"pickerdate"];
    [defaults synchronize];
    NSLog(@"The date is more than now. Pickerdate is %@",pickerdate);
}
else {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSCalendar*       calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
    NSDateComponents* components = [[NSDateComponents alloc] init];
    components.day = 1;
    NSDate * pickerdate = [calendar dateByAddingComponents: components toDate: self.picker.date options: 0];
    [defaults setObject:pickerdate forKey:@"pickerdate"];
    [defaults synchronize];
    NSLog(@"The date is less than now. Pickerdate is %@",pickerdate);
}

EDIT: Code modified, my logic was backwards but the problem remains.

Upvotes: 2

Views: 310

Answers (1)

rmaddy
rmaddy

Reputation: 318774

You can't use the >= (or similar) operator to compare two NSDate objects. These are objects. You must use the compare: method to compare the two dates. As you have it you are comparing to see if one object pointer is greater than or equal to another object pointer. Definitely not what you want.

The proper replacement would be:

if ([self.picker.date compare:[NSDate date]] != NSOrderAscending) {

Note that [NSDate date] gives the same result as [NSDate dateWithTimeIntervalSinceNow:0].

Upvotes: 1

Related Questions