2

Is there a way to override Equatable of NSManagedObject? I have a coredata dataset of 300k objects and I need to remove duplicates base on the object's business id.

// Coredata NSManagedObject
import Foundation
import CoreData

@objc(Business)
public class Business: NSManagedObject {

}

override error message:

enter image description here

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Unikorn
  • 1,140
  • 1
  • 13
  • 27
  • Related: https://stackoverflow.com/questions/33319959/nsobject-subclass-in-swift-hash-vs-hashvalue-isequal-vs – Martin R Jun 02 '19 at 05:31

2 Answers2

4

NSManagedObject already declares that it conforms to both Equatable and Hashable. No need to add the : Equatable.

You need to override the associated methods directly in your Business class without using the extension.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Was it `==` that needs to be implemented, or [`NSObjectProtocol.isEqual(_:)`](https://developer.apple.com/documentation/objectivec/nsobjectprotocol/1418795-isequal)? I can never remember it right – Alexander Jun 02 '19 at 02:01
-2

Since NSManagedObject already conforms to Equatable, why do you bother to conform to it again? :) Just override the == function and you are good to go!

extension Business {
    static func == (lhs: Business, rhs: Business) -> Bool {
        print("custom equation has been called")
        return lhs.id == rhs.id
    }
}

You can test it like so:

var b1 = Business()
var b2 = Business()
b1.id = "1"
b2.id = "2"

print("b1 == b2 ? \(b1 == b2)")

The result printed out proves your custom == function get called.

custom equation has been called
b1 == b2 ? false
Yiming Dong
  • 1,530
  • 2
  • 9
  • 11
  • 1
    This is invalid. You need to also override the implementation of `func hash(into:)`, otherwise you'll be violating the contract of `Hashable` (that equal values have equivalent hashes) – Alexander Jun 02 '19 at 02:00
  • 4
    [Methods and Properties You Must Not Override](https://developer.apple.com/documentation/coredata/nsmanagedobject#overview) checkout above link, which says you MUST not override == in NSManagedObject. also, something like this can be useful if you want unique results. https://developer.apple.com/documentation/coredata/nsfetchrequest/1506344-returnsdistinctresults – vinayak vanjari Jan 27 '20 at 13:16
  • It is bad practise to override a method via an extension as it's not clear what will get executed; the original or the extension. – Patrick Jan 06 '21 at 23:08