Why does NSString stringWithString return a pointer to the copied string?

I am trying to copy the NSString value from NSMutableArray to a new variable. NSString stringWithString returns an NSString with the same memory address as the object in my array. Why?

 #import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { NSMutableArray *arr = [NSMutableArray arrayWithObject:@"first"]; NSLog(@"string is '%@' %p", [arr objectAtIndex:0], [arr objectAtIndex:0]); // copy the string NSString *copy = [NSString stringWithString:[arr objectAtIndex:0]]; NSLog(@"string is '%@' %p", copy, copy); } return 0; } 
+4
source share
2 answers

1) Whenever you create a string using the @"" syntax, the structure automatically caches the string. NSString is a very special class, but the framework will take care of that. When you use @"Some String" in several places in your application, they will all point to the same address in memory. Only when you use something like -initWithData:encoding will the string not be cached.

2) Other answers suggested using -copy instead, but -copy will only create a copy of the object if the object is modified. (e.g. NSMutableString)
When you send -copy to an immutable object (like NSString), it will be the same as sending -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 point to the same memory address, only mutableCopy1 points occupy a different memory area.

+7
source

Since NSString instances are not mutable, the +stringWithString: method simply returns an input string with an incremental reference count.

If you really want to force create a new identical string, try:

 NSString * copy = [NSString stringWithFormat:@"%@", [arr objectAtIndex:0]]; 

This makes little sense if you don't need a pointer to be unique for some other reason ...

+4
source

All Articles