I’ve read apple documentation to assert that I was doing the memory management correctly but some questions raised.
Question 1:
They exhibit this code snippet as wrong :
in obj implementation:
- (NSString *)method1 {
NSString *string = [[NSString alloc] initWithFormat:@"%@ %@", firstName, lastName];
return string;
}
... later ...
NString* myString = [obj method1];
NSLog("%@", myString);
[myString release];
You own the string returned by alloc, but lose the reference to it before you get a chance to relinquish ownership. Following the memory management rules, this would result in a memory leak, since the caller has no indication that they own the returned object.
Since I’m taking care of releasing the object that has been allocated previously, there is no memory leak, right ? What do they mean by “lose the reference to it” ?
It is wrong only regarding apple’s memory management recommendations (the caller has no indication that they own the returned object) or this is also technically wrong ?
Question 2 :
This is about autoreleased objects availability :
Example code:
in obj1 implementation:
- (NSString *)methodA {
NSString *string = [[NSString alloc] initWithFormat:@"%@ %@", firstName, lastName];
return [string autorelease];
}
in obj2 implementation:
- (NSString *)methodB:(NSString *)inputString {
NSLog("%@",inputString)
//*other call of methods with arg inputString*//
}
... later ...
NString* myString = [obj1 methodA];
[obj2 method2:myString];
How far (or deep) following my functions calls will the autorelease object returned by obj1 will be available. Regarding apple’s documentations “Autorelease objects will be available within their variable scope”. Should I retain it at some point ?
Technically this is correct as you release
myStringafter using it. However if you follow Apples guidelines for method naming (strongly recommended), this is clearly wrong:method1doesn’t containcreate,alloc,neworcopy– thus per the guideline the caller doesn’t own the object and doesn’t have to release it.Auto-released objects will be alive until the closest Autorelease Pool is drained, see Autorelease Pools:
So, if you need your instances to stay alive after the corresponding autorelease pool was drained, take ownership by retaining them. Otherwise you usually just let them be handled by the pool.