How do I compare objects in Objective-C?

后端 未结 4 1759
长发绾君心
长发绾君心 2020-12-05 18:28

How do I compare two objects of a custom class? My idea was to add an additional method to the class in which I can compare the current object with another object of the sam

4条回答
  •  时光说笑
    2020-12-05 18:58

    The pointers to -isEqual: are good, but if you implement -isEqual:, you absolutely must also implement -hash in such a way that if two objects return YES for -isEqual: they will also return the same value for -hash. Implementing isEqual: without also implementing -hash leads to some very surprising bugs when you use Collections like NSArray.

    For new developers, I tend to recommend against overloading -isEqual:. I recommend instead using the same technique as NSString, and create a custom -isEqualToFoo: (where Foo is your class) until you understand the impact of -isEqual: on collections and specifically want this behavior. Overloading -isEqual: powerful, but the bugs you can create are subtle. Creating your own custom comparator is safer and clearer in many cases.

提交回复
热议问题