比较Obj-C中的对象 [英] Comparing objects in Obj-C
问题描述
如何比较Objective-C中的对象?
How does one compare objects in Objective-C?
像==一样简单吗?
我要检查对象数组,如果不存在,则将其添加到数组中,否则将其从数组中删除.
I want to check an array for an object and if it doesnt exist add it to the array otherwise, remove it from the array.
推荐答案
在Objective-C中比较对象的工作方式与Java或其他面向对象的语言几乎相同:
Comparing objects in Objective-C works much the same as in Java or other object-oriented languages:
-
==
比较对象引用;在Objective-C中,它们是否占用相同的内存地址. -
isEqual:
,在 NSObject ,检查两个对象是否相同".您可以重写此方法来为对象提供自己的相等性检查.
==
compares the object reference; in Objective-C, whether they occupy the same memory address.isEqual:
, a method defined on NSObject, checks whether two objects are "the same." You can override this method to provide your own equality checking for your objects.
因此通常要做的是,你会做的:
So generally to do what you want, you would do:
if(![myArray containsObject:anObject]) {
[myArray addObject:anObject];
}
之所以可行,是因为 NSArray 有一个称为containsObject:
的方法,该方法将isEqual:
消息发送到它包含的每个对象,并以您的对象作为参数.除非isEqual:
的实现依赖于==
,否则它不使用==
.
This works because the Objective-C array type, NSArray, has a method called containsObject:
which sends the isEqual:
message to every object it contains with your object as the argument. It does not use ==
unless the implementation of isEqual:
relies on ==
.
如果要完全使用实现的对象,请记住可以覆盖isEqual:
来提供自己的相等性检查.通常,这是通过比较对象的字段来完成的.
If you're working entirely with objects that you implement, remember you can override isEqual:
to provide your own equality checking. Usually this is done by comparing fields of your objects.
这篇关于比较Obj-C中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!