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 initWithRootViewController 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:
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:
alloc, you release it.copy, you release it.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.