0

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?

johnnyMac
  • 381
  • 2
  • 14
  • 1
    For instances of NSObject subclasses you should override `hash`, not `hashValue` – Martin R Aug 25 '17 at 05:29
  • In general, the isEqual method only needs to be called if the hash values of the objects to be compared are the same. But the advantage of hashing is the reduction of necessary comparisons and hash value for finding, inserting and removing values. However, the number of calls also depends on the actual implementation. – clemens Aug 25 '17 at 05:36
  • You're right guys, it's hash, not hashValue! Thanks – johnnyMac Aug 26 '17 at 16:53

0 Answers0