I’m trying to copy an NSString value out of an NSMutableArray into a new variable. NSString stringWithString is returning 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;
}
1) Whenever you’re creating a string using the
@""syntax, the framework will automatically cache the string.NSStringis 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
-copyinstead, but-copywill only create a copy of the object if the object is mutable. (like NSMutableString)When you’re sending
-copyto an immutable object (like NSString), it’ll be the same as sending it-retainwhich returns the object itself.–>
originalString,copy,mutableCopy2andanotherStringwill all point to the same memory address, onlymutableCopy1points do a different region of memory.