Could someone please advise me memory mgmt is needed or stringWithFormat is autoreleased. I have looked at NSString class reference docs on Apple Developer site, but can’t don’t see any clarification if a string copy is returned or is ‘msg’ a pointer only to autoreleased string.
NSString *msg; //pointer declared in interface
- (id) init
{
//some initialization code..
//is 'msg' receiving a copy or just a pointer assign
msg = [NSString stringWithFormat: @"%@ %@", FName, LName];
}
- (void) dealloc
{
//release some vars, properties here..
[msg release]; //is this correct ????
//Or should I be only doing: msg = nil;
[super dealloc];
}
Well the first problem is that your declared ivar
Will lose its value, because
[NSSTring stringWithFormat]according to the Cocoa Memory rules will return anautoreleasedobject. The rule states that any method name that contains alloc, new or copy will return an owned object, that is an object with aretaincount of 1, which means the receiver will own that object, any other method will return an autoreleased object. In your case if you did this instead:Now you own the object and you can send it a release message in dealloc
You should only send release to objects you own that is to objects you send a retain or copy message, in this case because you received an autorelease object, and you did not send a retain or copy message, therefore you must not sent it a release message. Sending a release message will cause a crash, since msg will be pointing to garbage by that point.