Understanding NSString comparison

后端 未结 7 1707
情歌与酒
情歌与酒 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:02

    The reason why == works is because of pointer comparison. When you define a constant NSString using @"", the compiler uniquifies the reference. When the same constants are defined in other places in your code, they will all point to the same actual location in memory.

    When comparing NSString instances, you should use the isEqualToString: method:

    NSString *myString1 = @"foo";
    NSString *myString2 = @"foo";
    NSString *myString3 = [[NSString alloc] initWithString:@"foo"];
    NSLog(@"%d", (myString2 == myString3))  //0
    NSLog(@"%d", (myString1 == myString2)); //1
    NSLog(@"%d", [myString1 isEqualToString:myString2]); //1
    NSLog(@"%d", [myString1 isEqualToString:myString3]); //1
    [myString3 release];
    

    Edit:

    NSString *myString3 = [[NSString alloc] initWithString:@"foo"]; 
    // this is same with @"foo"
    

    initWithString: does not create a new reference any more, you will need initWithFormat,

    NSString *myString3 = [[NSString alloc] initWithFormat:@"foo"];
    

提交回复
热议问题