I understand that any init... method initializes a new object and that NSString stringWithString makes a copy of the parameter string as a new object. I also understand that
What I don't understand is when would I use the stringWithString method since any local variable assigned that way would have it's memory "owned" by NSString instead of the local class.
A string created with stringWithString:
isn't owned by the NSString
, it is owned by the NSAutoreleasePool
(although multiple places can retain
an object, making ownership shared).
With stringWithString:
, the string will become invalid when the autorelease pool is next processed (normally during the application's next event loop) because the NSAutoreleasePool will release
its pointer. If you have not retain
ed the string before then, any pointer you have to it (name
in the case of your class) will be invalid (the variable name
will still exist but it will point to garbage).
Autorelease is good, if you don't intend to keep any pointers to the NSString
but since you do intend to keep a pointer, you'll need to retain
the NSString
. initWithString:
gives you a retain count of 1 automatically.