Making CoreData model hashable

Hopefully someone in here can help me out. I have created a class that conforms to hashable and equatable by making the corresponding functions such as:

static func ==(lhs: test, rhs: test) -> Bool {
return lhs.numberTest == rhs.numberTest

override public var hash: Int {

return self .numberTest


When I have these functions on my class and try to run it it crashes and gives me this error:
failed: caught "NSInternalInconsistencyException", "Class 'Test' for entity 'Test' has an illegal override of NSManagedObject -hash"

Hopefully someone can tell me what is going wrong and stir me into the right direction

NSManagedObject Explicitly requires you not to override hash (see Methods and Properties You Must Not Override).

I'd suggest that you work with numberTest directly.

1 Like

So check manually if I have a certain object do whatever I need to do and put it back?

Maybe, maybe not. It depends on your logic.
What you're trying to do ends up conflating two different notion of equality; record identity equality, and value-based equality.

If your logic dictates that every NSManagedObject will have different numberTest, you can mark the attribute as unique, and use it to uniquely identify NSManagedObject. Core Data will likely index numberTest automatically. You can then just use numberTest and cross CoreData to get NSManagedObject whenever needed.

Otherwise, you'll need to be able to handle multiple NSManagedObjects with the matching numberTest.

So yeah, check manually if you have one object matching, or with duplicates, or none at all.

How would I go about setting up the attribute as unique?

1 Like

Idk how to mark your reply as a resolved answer but thank you. What I am wondering now is when you do an update to a set it shouldn't b added if you got a unique number no?

If you're referring to when you save it to CoreData, it depends on the setting of managedObjectContext.mergePolicy. IIRC:

  • NSErrorMergePolicy (default) throws an error.
  • NSMergeByPropertyStoreTrumpMergePolicy will merge data one property at a time.
  • NSOverwriteMergePolicy will just force new data into the database.
  • NSRollbackMergePolicy will simply ignore new data.

This will (mostly) succeed if you have an existing record in the database, and you're saving a new data onto it (with duplicate numberTest). If you have two in-memory with the same numberTest, likely you'll get an error when you save.

What I am trying to do is update that class back into the set type Test. when I do update I don't want a duplicate. I could fix this by doing hashable but since I am doing core data with the Test Class I am unable to go this route.