If I declare a pointer variable in this fashion:
NSString *foo;
And then somewhere later in my code do something such as:
foo = @"bar";
Is that ultimately taking my NSString, creating a new copy in memory with an additional string, then deleting my initial string? Would foo be better off as an NSMutableString?
Best Answer
No,
foo
is variable holding a pointer to anNSString
. The assignmentfoo = @"bar"
sets the value stored by the pointerfoo
to the address of the NSString@"bar"
. There is no copy made. Iffoo
already pointed to an otherNSString
instance that was not a string constsant (i.e. like@"bar"
) and there are no other references to that instance, then you have a memory leak. You wouldin that case. You do not need to retain or release string constants like
@"bar"
.String constants cannot be mutated, so you will get a runtime error if you try to modify the value of a constant string. There's no difference between assigning
@"bar"
to anNSString*
vs anNSMutableString*
. Of course, you won't be able to use the mutating methods of theNSMutableString
without a runtime error just because you assign the address of @"bar" (an NSString instance) to a variable of typeNSMutableString*
. If you want to mutate the string, you would doIn this case, a copy is obviously made and you are responsible for releasing
mutableFoo
when you're done with it.