Handy equality testing method

Cocoa provides the nice standard -[NSObject isEqual:] method for comparing equality of two objects, which is very convenient, but introducing nil values can throw a spanner in the works. Namely, doing -[someNilVariable isEqual:nil] will return nil as the message was sent to a nil object. This might well be what you intended, but I find myself often wanting the reverse; two nil objects should be considered equal.

So, here's a nice simple NSObject category to handle that:

@implementation NSObject (MAEqualityAdditions) /* Like the standard -[NSObject isEqual:] method but can handle nil values. */ + (BOOL)object:(NSObject *)object1 isEqual:(NSObject *)object2; { BOOL result; if (object1 && object2) { result = [object1 isEqual:object2]; } else { result = (object1 == object2); } return result; } @end

Update: As ever, Omni have beaten me to it. If you check out their frameworks, there's already a very nice bunch of macros that do the above, but also handle NSNull.

© Mike Abdullah 2007-2015