What’s the right way to do this?
I have an array that I will use on several methods. I will add objects to it, get values, replace values, etc.
Today I do this:
I declare it on .h, using something like
NSMutableArray *myArray;
as soon as the application starts, I declare it on .m doing something like
myArray = [[[NSArray alloc] init] retain];
If I don’t add the retain the array will be released at some point and the application will crash. But allocating the array at the beginning of the application and left it “open” without releasing it will make instruments cry, pointing the finger at me, calling me a “leaker”…
How to solve that? Is this the correct way to do that? how do you guys do stuff like this?
thanks
allocimplicitly sets the retain count to 1. By sending theretainmessage you’re incrementing the retain count to 2. In order for the object to be deallocated you would then need to release it twice. Failure to do so would result in a memory leak.Ideally you should create the object in your
initmethod using[[NSArray alloc] init]and then release it in yourdeallocmethod like so:You might also find this article useful: http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html
One more thing: You declared myArray as an
NSMutableArraybut instantiated it as anNSArray. Perhaps that’s causing the crash.