I’m working on a game that has a game board, that is relatively small array of 4-array objects; a “poor-man’s matrix”. This array, which changes, persists throughout the game view controller, so it’s a property, with the retain attribute. I got the game functional, but recognized a lot of memory leaks when setting up the array.
Given this header file:
Basically, I was doing this:
Bad/Wrong way to do it
myChangingArray = [[NSMutableArray alloc] initWithObjects: obj1, obj2, obj3, nil];
Since I know you want to know, this is the right way to do it:
NSMutableArray *tmpArray = [[NSMutableArray alloc] initWithObjects:obj1, obj2, obj3, nil];
self.changingArray = tmpArray;
I have literally read these guidelines about 5 times, from Apple: Practical Memory Management I guess I didn’t really get it, because what sunk in for me was Erica Sadun’s The iPhone Developer’s Cookbook, p. 113 “… for normal (non-autorelease) objects, release the property after assigning it. ” That sounds so antithetical to what you want to do- keep a persistent object throughout the class. What it means is that you create a temporary object and once it’s got the right definition, assign it to the property. Because it is persistent, it already exists and you can’t initialize it. So instead, you create another object and copy it over. Most of the documentation and blog posts out there are about regular, easy to release quick and dirty variables, not retained properties. Hope this helps.