简体   繁体   English

如何比较两个对象是否真的是同一个对象?

[英]How to compare if two objects are really the same object?

I want to compare if an variable A represents the same object as variable B does. 我想比较一个变量A是否代表与变量B相同的对象。

Could I do that with the == operator? 我可以用==运算符吗?

Or what else is this exactly looking at? 或者这看起来还有什么? I think I need to check for the memory adress of the object where the variable is pointing to, right? 我想我需要检查变量所指向的对象的内存地址,对吧?

The == operator tests whether the two expressions are the same pointer to the same object. ==运算符测试两个表达式是否是指向同一对象的相同指针。 Cocoa calls this relation “identical” (see, for example, NSArray's indexOfObjectIdenticalTo: ). Cocoa将这种关系称为“相同”(例如,参见NSArray的indexOfObjectIdenticalTo:

To test whether two objects are equal, you would send one of them an isEqual: message (or a more specific message, such as isEqualToString: , if it responds to one), passing the other object. 要测试两个对象是否相等,您可以向其中发送一个isEqual:消息(或更具体的消息,如isEqualToString: ,如果它响应一个),则传递另一个对象。 This would return YES if you really only have one object (equal to itself, obviously) or if you have two objects that are equal. 如果你真的只有一个对象(显然等于它自己)或者你有两个相等的对象,那么这将返回YES In the latter case, == will evaluate to NO . 在后一种情况下, ==将评估为NO

The == tells you if two pointers are pointing to the same object. ==告诉您两个指针是否指向同一个对象。 isEqual tells you if the contents of two objects are the same (but not necessarily the actual same object). isEqual告诉您两个对象的内容是否相同(但不一定是实际的同一对象)。 A little confusing. 有点混乱。

Try this code to understand it better: 试试这段代码可以更好地理解它:

NSString *aString = [NSString stringWithFormat:@"Hello"];
NSString *bString = aString;
NSString *cString = [NSString stringWithFormat:@"Hello"];

if (aString == bString)
    NSLog(@"CHECK 1");

if (bString == cString)
    NSLog(@"CHECK 2");

if ([aString isEqual:bString])
    NSLog(@"CHECK 3");

if ([bString isEqual:cString])
    NSLog(@"CHECK 4");

// Look at the pointers:
NSLog(@"%p", aString);
NSLog(@"%p", bString);
NSLog(@"%p", cString);

[objectA isEqual:objectB] is usually a good choice. [objectA isEqual:objectB]通常是个不错的选择。 Note that some classes may have more specialized equality functions. 请注意,某些类可能具有更专业的相等功能。 ( isEqualToString: et.al.) These generally test not if they are the same object, but if the objects are equal, which is a distinct concept. isEqualToString: et.al。)这些通常不测试它们是否是同一个对象,但如果对象相等,这是一个独特的概念。 (Two string objects can be equal, even if they don't have the same memory address.) (两个字符串对象可以相等,即使它们没有相同的内存地址。)

The two other answers correctly answer the question in your title. 另外两个答案正确回答了标题中的问题。 The correct answer to the completely different question in your body text, however, is: yes, the == operator is correct for testing whether two variables refer to the same object . 但是,正文中完全不同的问题的正确答案是:是的,==运算符对于测试两个变量是否引用同一个对象是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM