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

前端 未结 4 540
感情败类
感情败类 2020-12-08 11:57

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

相关标签:
4条回答
  • 2020-12-08 12:16

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

    0 讨论(0)
  • 2020-12-08 12:17

    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.

    0 讨论(0)
  • 2020-12-08 12:19

    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);
    
    0 讨论(0)
  • 2020-12-08 12:20

    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.

    0 讨论(0)
提交回复
热议问题