Steve McLeod
Steve McLeod

Reputation: 52448

Clear description of NSArray isEqual method?

It is unclear to me how NSArray's isEqual method compares elements of the two arrays. Does it check if both arrays contain identical objects (eg. ==) ? or does it compare the contents of both arrays using isEqual on the objects?

I find Apple's docs for this method terse and unclear. I can't find the source for NSArray.m either.

Upvotes: 3

Views: 3270

Answers (4)

Daij-Djan
Daij-Djan

Reputation: 50089

MAYBE its kinda like this!? (typed here so there're likely typos)

if(![array1 isKindOfClass:[NSArray class]] || ![array2 isKindOfClass:[NSArray class]])
 return NO;

if(array1 == array2)
 return YES;

if(array1.count != array2.count)
 return NO;

for(int i =0; i<array1.count;i++)
 if(![array1[i] isEqual:array[i]])
  return NO;

return YES;

Upvotes: 1

Peter Hosey
Peter Hosey

Reputation: 96323

No answer exists in the modern Cocoa documentation, but if you go all the way back to WebObjects 3.5's NSArray documentation, you find this gem:

- (BOOL)isEqual:(id)anObject

Returns YES if the receiver and anObject are equal; otherwise returns NO. A YES return value indicates that the receiver and anObject are both instances of classes that inherit from NSArray and that they both contain the same objects (as determined by the isEqualToArray: method).

The closest thing to an answer outside of the legacy docs is this discussion of object comparison in the Coding Guidelines for Cocoa, which seems to imply that isEqual: and isEqualToWhatever: should do the same thing, with the only difference being the level of type safety.

Still, I recommend filing a bug to ask for the docs to be clarified.

Upvotes: 7

Jason Coco
Jason Coco

Reputation: 78353

All objects in Cocoa are compared with -isEqual: by default. The default version of -isEqual: on NSObject, however, does a pointer comparison. So, if the object hasn't properly implemented its -isEqual: and -hash methods, it's going to simply compare pointers.

Upvotes: 2

sch
sch

Reputation: 27506

The documentation is clear:

Two arrays have equal contents if they each hold the same number of objects and objects at a given index in each array satisfy the isEqual: test.

That means that isEqual (and not ==) wil be used to test objects for equality.

Upvotes: 4

Related Questions