15

Is date1 == date2 not a valid way to compare? If not, what is the correct alternative?

Here's my code:

- (NSDate*) dateWithNoTime {
    unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* components = [calendar components:flags fromDate:self];
    NSDate* dateOnly = [calendar dateFromComponents:components];
    return dateOnly;
}

- (BOOL) sameDayAsDate:(NSDate*)dateToCompare {
    NSDate *date1 = [self dateWithNoTime];
    NSDate *date2 = [dateToCompare dateWithNoTime];
    return date1 == date2;       // HERE IS WHERE THINGS SEEM TO FAIL

}
Trojan
  • 2,256
  • 28
  • 40
Greg
  • 34,042
  • 79
  • 253
  • 454

3 Answers3

44

You're comparing two pointer values. You need to use the NSDate comparison method like:

return ([date1 compare:date2] == NSOrderedSame);
Kirk Kelsey
  • 4,259
  • 1
  • 23
  • 26
8

As in the C language (of which Objective-C is a superset), the == (equality) operator compares two pointer values to see if they are equivalent (i.e. if two variables hold the same object). While this works in comparing primitive values (ints, chars, bools), it does not work on Objective-C objects, which might be equal in content, but differ in memory location (which is what the equality operator compares).

To check if two objects are equal, NSObject offers an -isEqual: method which you can use as a general statement (e.g. [date1 isEqual:date2]), and some classes choose to offer a more specific comparison method, such as -isEqualToDate: used to compare NSDates, or -isEqualToString: used to compare NSStrings. These methods cannot be used to compare primitive types (ints, for instance) because those are not objects, but will work on almost all objects.

Itai Ferber
  • 28,308
  • 5
  • 77
  • 83
5

You can't use == in Objective-C to compare object equality (it will take the C meaning, comparing pointers). Like other languages, you are simply comparing the object pointers.

The message you want is isEqualToDate:, aka [date1 isEqualToDate:date2]

Yann Ramin
  • 32,895
  • 3
  • 59
  • 82
  • 3
    "You can never use `==` in Objective-C" is a little harsh. Of course you can use it, just not for the purpose Greg is asking about. Yes, what you wrote is correct, but the wording is weird. – Itai Ferber Apr 12 '11 at 01:03
  • 1
    isEqualToDate checks exact equality so it will probably never return true. – jdog Dec 11 '12 at 20:45