Understanding NSString comparison

后端 未结 7 1693
情歌与酒
情歌与酒 2020-11-22 12:15

Both the following comparisons evaluate to true:

1)

@\"foo\" == @\"foo\";

2)

NSString *myString1 = @\"foo\";
NSStri         


        
7条回答
  •  难免孤独
    2020-11-22 13:09

    An example demonstrating how address comparison as a surrogate for string comparison will break:

        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
        NSString *s1 = @"foo";
        NSString *s2 = @"foo";
        NSString *s3 = [[[NSString alloc] initWithString:@"foo"] autorelease];
        NSMutableString *s4 = [NSMutableString stringWithString:@"foobar"];
        [s4 replaceOccurrencesOfString:@"bar"
                            withString:@""
                               options:NSLiteralSearch
                                 range:NSMakeRange(0, [s4 length])];
    
        NSLog(@"s1 = %p\n", s1);
        NSLog(@"s2 = %p\n", s2);
        NSLog(@"s3 = %p\n", s3);
        NSLog(@"s4 = %p\n", s4); // distinct from s1
    
        NSLog(@"%i", [s1 isEqualToString:s4]); // 1
    
        [pool release];
    

提交回复
热议问题