Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core data object comparison

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?

like image 375
nikkumang Avatar asked Feb 09 '10 03:02

nikkumang


2 Answers

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 committedValuesForKeys:allAttributeKeys] isEqual:[instance2 committedValuesForKeys: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.

like image 108
Barry Wark Avatar answered Oct 12 '22 15:10

Barry Wark


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".

like image 23
nevan king Avatar answered Oct 12 '22 16:10

nevan king