tags:

views:

53

answers:

2

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

+3  A: 

alloc implicitly sets the retain count to 1. By sending the retain message 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 init method using [[NSArray alloc] init] and then release it in your dealloc method like so:

- (void)dealloc {
    [myArray release];
    [super dealloc];
}

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 NSMutableArray but instantiated it as an NSArray. Perhaps that's causing the crash.

robinjam
thanks but tell me this: am I committing an heresy for declaring the array at the beginning of the app and releasing it on the dealloc method? How can I not use retain? If I don't the array will be invalid and the application will crash. I have tried to remove the retain, but the app crashes.
Digital Robot
You must be releasing it somewhere else in your code. Make sure the only instance of `[myArray release]` in your code is in your `dealloc` method.
robinjam
+2  A: 

You should not retain the object you've just created. You already own it. If, as you say, "the array will be released at some point and the application will crash," that is the code you should change. Your code shouldn't be releasing an object that you still want to keep around.

Chuck
thanks!!!!!!!!!!!
Digital Robot