3

I have two NSArrays each containing NSStrings. I need to test whether the two arrays are equal. In this instance, equality means not that the arrays contain the same objects, but that each object returns true for isEqualToString when compared its counterpart. The arrays are also not equal if one contains more items than the other, or the order of the items is different.

Can I assume isEqualToArray won't help me here?

Similarly, I don't see an approach using NSSet that would fulfill all of the criteria.

How might I test the equality of these two arrays?

5
  • 1
    Look at the docs. isEqualToArray: uses isEqual: on each pair of objects. Commented Oct 18, 2012 at 17:33
  • Does isEqual always return the same as isEqualToString for NSStrings? Commented Oct 18, 2012 at 17:35
  • 1
    If it doesn't, then NSString is broken. Again, look at the docs for isEqualToString:. Commented Oct 18, 2012 at 17:35
  • I've read the NSObject protocol and I see that each NSObject defines what it means to be equal. I think what's getting in my way is why isEqualToString exists if isEqual does the same thing. Commented Oct 18, 2012 at 17:54
  • 1
    @BenPackard: isEqualToString is a tiny bit faster than isEqual if both objects are strings (because the method doesn't check at runtime to see if they are both strings). Commented Oct 18, 2012 at 18:03

1 Answer 1

9

The docs for isEqualToArray state:

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 seems like it fits your criteria.

Sign up to request clarification or add additional context in comments.

3 Comments

So does [obj1 isEqual:obj2] return the same as [obj1 isEqualToString:obj2] if obj1 and obj2 are both NSString?
Be aware that isEqual when applied to NSStrings returns YES if the two object are NSStrings without actually comparing the contents. To be sure that two arrays contains the same strings in the same order you will need to loop through each using isEqualToString:
@MyTallest: -[NSString isEqual:] will call -[NSString isEqualToString:] if both objects are strings; otherwise, it will return NO.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.