Copy NSString not copying?

NSString *myString = @"sample string"; NSString *newString = [myString copy]; 

If I set a breakpoint after these two lines, the pointer to myString will be the same as the pointer to newString.

WTF? Is it not supposed that a copy of NSString will return a pointer to a new object? Or am I missing something fundamental about how a copy should work?

+6
objective-c iphone nsstring
source share
4 answers

Since NSString does not change , it can just increment the ref count and do with it.

When you release one of these NSStrings, it can simply reduce the ref count - standard memory management.

Do you see any problems with this?

+9
source share

Think about it: NSMutableString is a subclass of NSString . When your property is declared as NSString , you do not expect it to change.

Keep in mind that if you used retain and someone gave you NSMutableString and then changed it, your class will be broken.

However, you may think that copy always slower. Therefore, NSString copy simply calls retain . NSMutableString copy makes the actual copy.

It’s usually best to spit out NSString * because people don’t have to copy them all the time.

+6
source share

It is best to copy the string value returned by the method, since the return value can be a mutable string object, and this value can be changed in another thread after the method returns.

+1
source share

You can select a new variable, as in the example

 NSString *anotherString = [[NSString alloc] initWithString:originalString]; 
+1
source share

All Articles