I see a lot of code, particularly in Apple example code, that resembles the following:
EditingViewController *controller = [[EditingViewController alloc] initWithNibName:@'EditingView' bundle:nil]; self.editingViewController = controller; [controller release];
Is there any reason in particular that the approach above proves beneficial over:
self.editingViewController = [[EditingViewController alloc] initWithNibName:@'EditingView' bundle:nil];
Trying to understand if there is a strategy for the above.
Thanks!
On first glance, it would seem that your example would work, but in fact it creates a memory leak.
By convention in Cocoa and Cocoa-touch, any object created using
[[SomeClass alloc] initX]or[SomeClass newX]is created with a retain count of one. You are responsible for calling[someClassInstance release]when you’re done with your new instance, typically in yourdeallocmethod.Where this gets tricky is when you assign your new object to a property instead of an instance variable. Most properties are defined as
retainorcopy, which means they either increment the object’s retain count when set, or make a copy of the object, leaving the original untouched.In your example, you probably have this in your
.hfile:So in your first example:
But for your second example:
By calling the
autoreleasemethod on your new object before passing it to the setter, you ask the autorelease pool to take ownership of the object and release it some time in the future, so for a while the object has two owners to match its retain count and everything is hunky dory.Another option would be to assign the new object directly to the instance variable instead of the property setter. Assuming your code named the underlying instance variable
editingViewController:That’s a subtle but critical difference in the code. In these examples,
self.editingViewController = xis syntactic sugar for[self setEditingViewController: x]buteditingViewControlleris a plain old instance variable without any retain or copy code generated by the compiler.See also Why does this create a memory leak (iPhone)?