简体   繁体   中英

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.

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: ).

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. This would return YES if you really only have one object (equal to itself, obviously) or if you have two objects that are equal. In the latter case, == will evaluate to 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). 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. 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. (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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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