Understanding NSString comparison

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

Both the following comparisons evaluate to true:

1)

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

2)

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


        
7条回答
  •  青春惊慌失措
    2020-11-22 12:53

    The equality operator == only compares pointer addresses. When you create two identical strings using the literal @"" syntax, the compiler will detect that they are equal, and only store the data once. Hence, the two pointers point to the same location. However, strings created by other means may contain identical data, yet be stored at different memory locations. Hence, you should always use isEqual: when comparing strings.

    Note that isEqual: and isEqualToString: always return the same value, but isEqualToString: is faster.

提交回复
热议问题