2

How do I compare two objects of a custom class in Objective-C? I try to overloading the

- (NSComparisonResult)compare:(id)other;

method. This works great if I call the method manually

if ([obj1 compare:obj2] == NSOrderedDescending) {  
    // do something  
}  

Is there any way that I can do it like this?

if (obj1 > obj2) {
    // do something
}

Or is there another method that I need to overload?

Sherm Pendley
  • 13,556
  • 3
  • 45
  • 57
user691219
  • 173
  • 1
  • 4
  • What are you planning to do with the comparison? In case you want to insert individual items in a sorted order into a collection I recommend taking a look at `indexOfObject:inSortedRange:options:usingComparator:`. It is available for `NSArray` in Mac OS X v10.6 and later. – JJD Apr 04 '11 at 16:12

2 Answers2

8

This is not possible, since objective C doesn't have operator overloading. You are comparing pointer values.

mvds
  • 45,755
  • 8
  • 102
  • 111
  • Thank you for the statment. Now I can understand why comparing with > sometimes seems to work. Next time I will try not to compare pointer value. :) – user691219 Apr 06 '11 at 21:52
0

One way to achieve this is for your class you can define comparisons to everything that make sense to compare with.

@interface MyClass : NSObject
{
    // your stuff
}
- (BOOL)isGreaterThanNumber:(NSNumber *)otherNumber;
+ (BOOL)compare:(MyClass *)myClass toNumber:(NSNumber *)otherNumber;

With well-named functions this isn't terribly different than overloading although yes it prevents you from using > and <. The actual code you write should be identical though as if overloading were included.

Nektarios
  • 10,173
  • 8
  • 63
  • 93