How to know who will take ownership?
Recipe example
RecipeAddViewController *addController = [[RecipeAddViewController alloc]
initWithNibName:@"RecipeAddView" bundle:nil];
addController.delegate = self;
Recipe *newRecipe = [NSEntityDescription
insertNewObjectForEntityForName:@"Recipe"
inManagedObjectContext:self.managedObjectContext];
addController.recipe = newRecipe;
UINavigationController *navigationController = [[UINavigationController alloc]
initWithRootViewController:addController];
[self presentModalViewController:navigationController animated:YES];
[navigationController release];
[addController release];
presentModalViewController and in开发者_StackOverflowitWithRootViewController are retaining their arguments and taking ownership. Then two objects are released, proving that someone took the ownership. So in general how do I know which message will in result take ownership, to release the corresponding objects?
newRecipe is not released because the life-cycle of managed object is non of my business, is this statement correct?
UPD: sorry for #2 the answer would be that it's retained by addController then released in dealloc of addController.
The rule, in its simplest form would be:
If you retain it, you release it.
However, by retain I really mean "increase retain count," and therefore creating a new object (unless it's autoreleased) counts as a retain, too.
So:
- If you called
alloc
, you release it. - If you called
copy
, you release it. - If you called
retain
, you release it.
Other than these three cases, you shouldn't worry about releasing (assuming the third-party libraries you use follow the naming conventions). However, if you must know what's being retained and what's not being retained, you can check the documentation for the class in question.
For your example:
Factory methods (like
[NSString stringWithFormat:]
) create autoreleased objects. As a rule of thumb, if it's a class method that begins with the name of the class, it returns an autoreleased object.insertNewObjectForEntityForName:inManagedObjectContext:
returns an autoreleased object. This is in the documentation for NSEntityDescription.delegates are almost never retained, in order to prevent retain cycles.
With the exception of delegates, you don't need to care about what goes on in a class. If you pass it a property, it's its job to retain or copy it if it needs to. All you need to care about is balancing your retains and releases.
The Cocoa Memory Management rules tell you all you need to know.
To answer your questions:
You don't care what other objects are doing in terms of release/retain. Assume they follow the rules, and you'll be OK (or it's a bug in their code).
you should not release newRecipe because you didn't obtain it with new, alloc or a method containing copy. Also you did not retain it.
精彩评论