I have been programming in Objective-C for a couple weeks now, and I think its time that I think more about my memory management and so I have a couple scenarios I would like clarification on.
NSString *myString = @"Hello, World";
If I were to on the next line do
NSString *anotherString = myString;
Is it getting copied? or is another string just a pointer to myString? if it’s just a pointer how would I make anotherString a copy of myString that has its own memory?
What if I were to
[anotherString release];
What actually gets released, just anotherString, or does myString go away too?
Then if I were to do
anotherString = nil;
Does that actually free up memory and for use or does it still have the space allocated with empty memory? Obviously the pointer can still be used. What does it do to myString?
This will really help me become better at managing the memory properly, instead of just [object release]; randomly and causing crashes.
Thank you VERY MUCH in advance to whoever replies.
When you do:
…you’re creating a single
NSStringinstance, and two pointers to it. So to answer your questions, no it is not being copied. Yes,anotherStringis just a pointer, and so ismyString, the actualNSStringinstance is off in memory-land, at the address that both pointers are now pointing to.To make a copy of the string, you would do:
When you do:
The
NSStringinstance thatanotherStringpoints to is released. Nothing happens toanotherStringitself. It continues to point to your now-invalidated object instance. IfmyStringwas pointing to the same instance, then yes, this causesmyStringto “go away” as well.And if you do:
…then you’ve caused a memory leak, because you reassigned the pointer without releasing the thing it was pointing at. Except not in this case because
@"Hello, World"is a literal value that is loaded onto the stack and is not retained by your code.In any case, setting
anotherStringtonildoes nothing to your string, it just changes whatanotherStringpoints to. Your actualNSStringinstance is still off in memory-land, completely unaware that you just threw away your reference to it (possible exception: reference counted/garbage collected environments).And yes, calling
[object release]randomly will cause crashes. As a general rule you should only callreleaseon something if:allocandinit...on it.retainon it.copyon some other object.Note that these stack, so if you
allocsomething,retainit, and thencopyit, you need to have 3 calls torelease, two for the object that youalloc‘ed, and one for the copy.As a side note, you may find it clearer to write your object declarations like:
…which makes it more obvious that what you are declaring are pointers to NSString’s and not NSString’s themselves. Personally I think your original syntax, while commonly used, is also backwards.