Why is NSString stringWithString returning pointer to copied string?

后端 未结 2 1912
你的背包
你的背包 2021-01-19 09:42

I\'m trying to copy an NSString value out of an NSMutableArray into a new variable. NSString stringWithString is returning an NS

2条回答
  •  粉色の甜心
    2021-01-19 10:11

    1) Whenever you're creating a string using the @"" syntax, the framework will automatically cache the string. NSString is a very special class, but the framework will take care of it. When you use @"Some String" in multiple places of your app, they will all point to the same address in memory. Only when you're using something like -initWithData:encoding, the string won't be cached.

    2) The other answers suggested that you should use -copy instead, but -copy will only create a copy of the object if the object is mutable. (like NSMutableString)
    When you're sending -copy to an immutable object (like NSString), it'll be the same as sending it -retain which returns the object itself.

    NSString *originalString = @"Some String";
    NSString *copy = [originalString copy];
    NSString *mutableCopy1 = [originalString mutableCopy];
    NSString *mutableCopy2 = [mutableCopy copy];
    NSString *anotherString = [[NSString alloc] initWithString:originalString];
    

    --> originalString, copy, mutableCopy2 and anotherString will all point to the same memory address, only mutableCopy1 points do a different region of memory.

提交回复
热议问题