Re: Alloc/dealloc etiquette
Sherm Pendley <[email protected]> Sat, 17 Feb 2007 01:07:05 -0500
| Newsgroups | gmane.comp.lib.gnustep.user |
|---|---|
| Message-ID | <[email protected]> |
Michael Ash <[email protected]> writes: > Override -dealloc if you have any instance variables pointing to objects > that you own. This all comes down to memory management; if at some point > you allocated, copied, or retained an object and put it in an instance > variablel, you should release it here. A minor nit - I prefer to release instance variables (if they're objects) in their accessor methods. One common way to do this is with the accessors that can be automatically generated by Xcode: - (void)setFoo:(NSObject *)value { if (foo != value) { [foo release]; foo = [value copy]; } } There are many variations on this theme of course - and at least one utility (Accessorizer) to help manage them all. What they all share though, is the goal of placing the retention action (a -copy in this case) in the same place as its matching release. It's a simple pattern; if you want to refer to some- thing later, you store a reference to it using an accessor. The accessor will, at the same time, take care of releasing any previous references if needed. A great deal of confusion seems to come out of not using this pattern, and scattering memory management code everywhere - often seemingly at random - instead. To support this pattern, I don't use -release in -dealloc. Instead, I'd use the accessor there as well: [self setFoo:nil]; sherm-- -- Web Hosting by West Virginians, for West Virginians: http://wv-www.net Cocoa programming in Perl: http://camelbones.sourceforge.net