I've already voted on the correct answer, I'm adding this as a style note:
Your calling code isn't going to work, because it is calling [object description]
when it should be calling [object test]
You don't need to be returning mutable strings unless you really want to be able to change the string. I personally try to minimise mutability in the code I write because I feel it is easier to maintain programs where state changes are minimal. You are only returning a description so I don't think it needs to be mutable. I know this is only some example code so maybe I'm being too picky
You could rewrite this as:
-(NSString *)description {
// Just return a static NSString. No need to worry about memory management.
return @"Test Value";
}
And if you want to be able to change the value of this returned string in your calling code:
NSMutableString *testVar = [[NSMutableString alloc]initWithString:[object description]];
Since you've called alloc on this string, you own it and are responsible for releasing it at some future date.
Alternatively, you can use one of my favourite bits of code:
NSMutableString *testVar = [[object description] mutableCopy];
This will return a mutable copy of even an immutable object (if it conforms to the NSMutableCopying protocol, of course). And you need to send [testVar release]
at some stage.
And to tie this in as an actual answer to your question: if you send alloc, copy, mutableCopy, or retain to an object, then you own the object and are responsible for sending it a release message. You can assume that anything else returns an autoreleased object.
Again, I know this is only a quick bit of sample code that you asked a question on, but if you follow the above rule you've got most of your memory management problems sorted. In your first example you sent none of these for messages, so you don't need to release any memory yourself. However, you have an alloc
in your calling code, so you own testVar
and you need to release it.