How to override hash and isEqual for NSManagedObjects?
Asked Answered
S

1

6

We have a bunch of NSManagedObjects of various types. Some of them have members that are NSSet's of other NSManagedObjects. The problem is that I really need to override the hash and isEquals methods of the objects that are IN the set - but they are NSManagedObjects. I'm having problems with getting multiple identical objects in the set. As far as I can tell, since hash defaults to the object address - all objects are different. So I need to override hash and isEquals - but can't see any way to do it.

What we have is a bunch of stuff in the System, and more comes in via XML - sometimes repeats of the existing objects. When they are the same, I don't want dups added to the set.

Sacrilege answered 26/4, 2013 at 23:21 Comment(5)
You explicitly can not override isEqual or hash on NSManagedObject.Piaffe
So, that means the NSSet's that are created can't really be treated as NSSets? bleh.Sacrilege
It depends how you're defining equality. If the objects are equal why do you have different instances for each?Piaffe
Have a look at this question: #11554638Ornithosis
I could have sworn I replied to this 2 days ago... The other question refd by batkuip doesn't seem to be really relevant. There are dups because I'm loading a big block of XML, and the server sometimes re-sends an object. So I want to prevent the dups from being added.Sacrilege
M
1

As mentioned above by Wain, NSManagedObject documentation states that you must not override hash or isEqual:. So this means a stock NSSet does not do what you need.

Some of your options are:

  • Enumerate the NSSet contents to identify and remove duplicates
  • Write a factory method for your NSManagedObjects that will return the same object when given the same inputs
  • Fix the XML to not include duplicated objects
  • Unique the objects coming from the XML before they become NSManagedObjects
  • Modify the input XML to include a unique identifier that you can track, assuming the duplicated objects are exact duplicates
  • Implement your own NSSet-like collection class that performs a different uniquing test than hash and isEqual:
Matthei answered 28/9, 2013 at 9:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.