Mutable array comparison for copied objects

此生再无相见时 提交于 2020-01-07 00:04:46

问题


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:


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)




回答2:


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.



来源:https://stackoverflow.com/questions/21109077/mutable-array-comparison-for-copied-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!