views:

721

answers:

2

Is there an easy/generic way to compare two objects to see if they are the same? By 'same' I mean identical entity name, all attributes and relationships are the same, but the internal object ID is different.

Similarly, is there an easy/generic way to find the differences?

+1  A: 

You might want to read through this article:

http://moottoot.blogspot.com/2008/02/core-data-and-uniqueness.html

NSManagedObject has a method isEqual: which you are not allowed to override. Have you tried using this method to check if it returns for different kinds of objects? Various classes override this (NSObject) method so that the "equal" means either "the same objects" or "objects with the same contents".

nevan
+2  A: 

Do you need to recursively include equality of relationships (i.e. relationships point to destinations that are equal by your definition)? Do you need to test equality across managed object models? Do you need to test uncommitted values? Assuming the answer is "no" to all these, the solution isn't too hard...

instance1 is equal to instance2 by your definition if:

NSArray *allAttributeKeys = [[[instance1 entity] attributesByName] allKeys];

if([[instance1 entity] isEqual:[instance2 entity]]
&& [[instance1 commitedValuesForKeys:allAttributeKeys] isEqual:[instance2 commitedValuesForKeys:allAttributeKeys]]) {
  // instance1 "==" instance2
}

If the answer to any of the above questions is "yes", the solution is significantly more complex.

Caveat

I'm not sure any of this is a good idea. You probably want to rethink your design if you need to use the solution above. There are almost certainly better ways to do what you're trying to do that don't run the risk of running afoul of Core Data's intentions.

Barry Wark
While this is a solid solution I most strongly agree with your Caveat. If you are having to compare every value in one object to another to see if you are duplicating data then there is something wrong in the design and you need to re-think it.
Marcus S. Zarra