0

I am currently working on an demo app so I was a little sloppy how to get things done, however I run the "Build and Analyze" to see how many leaks I get,... well and there are a lot.

Source of teh proble is that I have a NSMutableArray and I add some Objects to it :

NSMutableArray *arr = [[NSMutableArray alloc] init];
[arr addObject:[[MyObject alloc] initWithText:@"Option1"]];
// I have like 100 lines like that and 100 complains

Now, xcode complains about a potential leak.

Can someone give me some advice how to handle that ?

Thanks.

1

2 Answers 2

3

The problem is that you're allocating an instance of MyObject which you have a responsibility to release. When you pass it to the array, the array also retains the object, so now both you and the array have to release it. You can simply autorelease the object, and the array will keep it retained until you remove the object from the array or destroy the array itself.

[arr addObject:[[[MyObject alloc] initWithText:@"Option1"]] autorelease];
Sign up to request clarification or add additional context in comments.

Comments

2

Replace

[arr addObject:[[MyObject alloc] initWithText:@"Option1"]];

with

[arr addObject:[[[MyObject alloc] initWithText:@"Option1"] autorelease]];

Most collections (arrays, dictionaries) own the objects added to them. And, since you’ve sent +alloc to MyObject, you also own the object that’s just been instantiated. As the memory management rules say, you are responsible for relinquishing ownership of objects you own. Sending -autorelease to the newly instantiated object will do that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.