问题描述
如何比较自定义类的两个对象?我的想法是在类中添加一个额外的方法,使我可以将当前对象与另一个相同类型的对象进行比较.
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 same kind.
所以我可以编写自己的代码,比较类的每个字段.
So I can write my own code how each field of the class is compared.
这就是我要做的.还是有一些预定义的方法可以做到这一点?像NSString类的"isEqualTo"一样?
This is how I would do it. Or are there some predefined methods to do that? Like "isEqualTo" of the NSString class?
推荐答案
指向-isEqual:
的指针是好的,但是如果实现-isEqual:
,则绝对必须还要在其中实现-hash
这样,如果两个对象为-isEqual:
返回YES
,它们也将为-hash
返回相同的值.在不使用-hash
的情况下实现isEqual:
的情况会导致在使用诸如NSArray之类的Collection时出现一些非常令人惊讶的错误.
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.
对于新开发人员,我倾向于建议不要重载-isEqual:
.我建议改为使用与NSString相同的技术,并创建一个自定义-isEqualToFoo:
(其中Foo
是您的类),直到您了解-isEqual:
对集合的影响并特别希望这种行为.重载-isEqual:
功能强大,但是您可以创建的错误非常微妙.在许多情况下,创建自己的自定义比较器会更安全,更清晰.
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.
这篇关于如何在Objective-C中比较对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!