I have a problem with memory leak warning when releasing an object after returning it. I read a few posts about the similar subject but in those posts problem with releasing was that in the end “they” didn’t really own the objet they were releasing.
If I use autorelease while initializing that same object I get no problems. My question is: if Apple suggests releasing manually all the objects that we created, how come I get this warnings?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
//Display no cells until it loads
if([items count] < numberOfItemsToDisplay){
UITableViewCell *cell = [[[UITableViewCell alloc] init]autorelease];
return cell;
//[cell release];
}
I have no problems autoreleasing objects but I hate not understanding things I thought I understood 🙂
Thanks, L
After return statement function is returned and nothing further is executed. So release after return will not execute. So you will leak memory. And you can not release before the return as the caller will use that object. So you really can’t release that before return. So you have two ways to handle this situation. 1st option is to make the returned object autorelease. Another option is to make the function name in such a way that the caller know that it owns the returned object and must release it.
Check Returning Objects from Methods from Memory Management Programming Guide for the details explanation of this case.