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

前端 未结 4 549
感情败类
感情败类 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: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);
    

提交回复
热议问题