Reputation: 541
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];
}
Upvotes: 0
Views: 660
Reputation: 82257
If you are using ARC, you don't need to do anything at all in that case. ARC will handle it for you. If you are NOT using ARC then your code may crash as the msg variable will be released automatically at the end of the run loop.
In a non-ARC case you should use:
msg = [[NSString stringWithFormat: @"%@ %@", FName, LName] retain];
- (void) dealloc
{
[msg release];
msg = nil;
...
Or better, use a property instead.
Upvotes: 1
Reputation: 18488
Well the first problem is that your declared ivar
NSString *msg;
Will lose its value, because [NSSTring stringWithFormat]
according to the Cocoa Memory rules will return an autoreleased
object. The rule states that any method name that contains alloc, new or copy will return an owned object, that is an object with a retain
count 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:
msg = [[NSString stringWithFormat: @"%@ %@", FName, LName] retain];
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.
Upvotes: 1