user2990765
user2990765

Reputation: 387

Mutable array comparison for copied objects

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.

Upvotes: 0

Views: 352

Answers (2)

malex
malex

Reputation: 10096

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.

Upvotes: 0

David Rönnqvist
David Rönnqvist

Reputation: 56625

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)

Upvotes: 2

Related Questions