开发者

iphone - not leaking

开发者 https://www.devze.com 2023-01-05 01:01 出处:网络
What\'s the right way t开发者_如何学Co do this? I have an array that I will use on several methods. I will add objects to it, get values, replace values, etc.

What's the right way t开发者_如何学Co 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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号