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.

eemceebee
  • 2,656
  • 9
  • 39
  • 49
  • You own any object you create (http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmObjectOwnership.html%23//apple_ref/doc/uid/20000043-SW1) Are you releasing arr at any point? Finally, you would do better to create your object apart from the addObject method, pass it in addObject and then release it (see the answer here: http://stackoverflow.com/questions/179665/nsmutablearray-destruction for more) – ndtreviv Jan 11 '11 at 15:45

2 Answers2

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];
filipe
  • 3,370
  • 1
  • 16
  • 22
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.