0

I am trying to do array comparison on 2 mutable arrays. In one of the array, i am storing my model objects and in the other array I am storing a copy of the model objects using [myObject copy]. My model object is a subclass of NSObject so I have added the copyWithZone: method as well. However when I do array compare using isEqualToArray on these two arrays it always returns false. Will the compare not work on copied objects? Or am I going wrong somewhere else?

P.S: As an overview, what I'm trying to do is to check whether something is changed in my model before calling an update service. I want to call the service Only if any of the model objects have changed.

1
  • Just some reading on the matter NSHipster Commented Jan 14, 2014 at 9:04

2 Answers 2

2

Will the compare not work on copied objects?

You can very easily find out the answer to this question by just copying a single object and checking for equality agains the original.

SPOILER

The results you are going to see will depend on if you have implemented custom hash and isEqual: methods in your class. Without those it will default to the superclasses implementation (NSObject) which considers equality to be the same pointer. Since a copy is a new pointer to the same object, NSObject won't consider them equal.

I would recommend that you read about object equality in this NSHipster article (great to start with) and/or in this article by Mike Ash (if you are feeling curious)

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

4 Comments

Thanks for the update. I have not implemented hash and isEqual methods and as you pointed out when I compared the copy directly it is returning false. Any pointers to implement custom hash and isEqual methods would be helpful. Or otherwise any other approach which would satisfy my requirement posted as P.S im my question would be welcome.
@user2990765 I just updated my answer with links to two really good articles about custom hash and isEqual.
@DavidRönnqvist: See stackoverflow.com/editing-help#spoilers how to format a spoiler :-)
@MartinR I didn't know there was such a thing :D
0

Method isEqualToArray acts as follows. It takes one by one the next objects from two arrays and compare them using isEqual. The latter compares hash (NSInteger property) of NSObjects (or its subclasses). In general it is the address of the object. hash can be redefined while subclassing but it may cause big problems. For copied objects you will have different hashes. And thus isEqualToArray is always FALSE.

But if you use simple data classes like NSNumber, NSString as elements to compare, you will get TRUE under copying them.

Comments

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.