Should I generally always retain or copy a string value returned from a function?
Consider the following examples:
- (NSString*) getString:
{
return [[NSString alloc] autorelease];
}
- (NSString*) getStringAlloc: // Not sure if this convention is correct
{
return [NSString alloc];
}
...
In the calling method
NSString* myString = [self getString];
If I want to go on and use myString in the function without it getting released how do I handle it. Also is the name of the second method using the correct conventions.
If I knew the returning string was autoreleasing (from the method name) and it wasn’t being changed then presumably the only reason to retain or copy would be so someone didn’t change the code in the future. If I didn’t mind the value changing then, again I presumably don’t need to retain or copy.
Assuming I am not using ARC.
No! The scope in which an object is created (your method “getString” in that case) is also responsible for releasing it! So the first approach is the only valid approach.
Also getter-methods are NOT prefixed with “get” by convention. So the method should be called
- (NSString*) stringinstead.