NSMutableOrderedSet function "contains(_ object: Any)" does not always call the object's isEqual method

66 Views Asked by At

var entries:NSMutableOrderedSet //contains DataEntry objects

I'm adding seven objects to this ordered set using this function:

func dataAssignment(data: Any) {

        if let dict = data as? [String:DataEntry] {

            entries.removeAllObjects()
            for value in dict.values {

                entries.add(value)
            }
            sort()
        }
    }
}

This is the DataEntry class:

open class DataEntry: NSObject {

    var title:String
    var text:String
    ...
}

extension DataEntry { //Equatable 

    open override func isEqual(_ object: Any?) -> Bool {

        guard let object = object as? DataEntry else { return false }
        return title == object.title
    }

    override open var hashValue: Int {

        return title.hash
    }
}

To this ordered set I'm adding more objects, but only if the objects are not already part of the ordered set (because I want to notify interested parties if new objects have been added). I'm using this to add:

func dataAddition(data: Any) {

            guard let entry = data as? DataEntry else {return}

            if !self.entries.contains(entry) { //THIS FAILS

                self.entries.add(entry)
                self.sort()
            }
            else {

                let entry = data as! DataEntry
            } 
}

Only sometimes DataEntry's isEqual function will be called, but why not always? This results in duplicates.

Also, when self.entries.add(entry) is executed, the isEqual function is called more than seven times (10 to 13 times). Why?

0

There are 0 best solutions below