开发者

Objective-C memory leak, memory management question

开发者 https://www.devze.com 2023-03-10 12:09 出处:网络
I am new to Objective C and believe I have a memory leak situation in this function, but I am not sure when to delete/release the objects.

I am new to Objective C and believe I have a memory leak situation in this function, but I am not sure when to delete/release the objects.

Since I store the recipeObject into my View, I free it in the dealloc of the view, but I am not sure about the view?

- (void)tableView:(UITableV开发者_如何学JAVAiew *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    RecipeObject * recipeObject = (RecipeObject *)[maRecipes objectAtIndex:indexPath.row];
    RecipeView * recipeView = [[RecipeView alloc] initWithNibName:@"RecipeView" bundle:nil];
    [recipeView setRecipeObject:RecipeObject];  
    [self.navigationController pushViewController:recipeView animated:YES];
}

Can someone show me an example of what to do, or explain it?


The first rule to remember when you're dealing with memory management in Objective-C is that you're responsible for anything that you (1) allocate (using alloc), (2) new up (using new), (3) copy (using copy), or (4) retain (using retain). In those four cases, you must explicitly release (or autorelease) those references.

In your example, since you allocated recipeView, you must release it once it's added to the navigation controller.

RecipeView * recipeView = [[RecipeView alloc] initWithNibName:@"RecipeView" bundle:nil];
[self.navigationController pushViewController:recipeView animated:YES];
[recipeView release];

If you don't do this, you'll leak recipeView since it goes out of scope once the method exits and you will no longer have a way to access the allocated space on the heap.

Does that make sense?


You must release recipeView after the pushViewController. When pushing it a retain is done, then when popping a release is done.


Add this to the last line of the code

[recipeView release];
0

精彩评论

暂无评论...
验证码 换一张
取 消