0

I have a class which contains an NSMutableArray called _contents. This array is initialised on creation of an instance of this class, and there is a method setContentsObject: to add an object to the contents. This is the implementation of setContentsObject:

- (void)addContentsObject:(id <MyProtocol>)object
{
    [_contents addObject:object];
}

Pretty simple, and it works, but when I analyse the running of my app using the Leaks instrument, I get a reported leak (labeled '100%') on the one line of that method. I understand that addObject: retains the object, but I've never had this issue before and I don't see what more could be done to this method.

2
  • 3
    Maybe your array is never released. Or maybe the objects you're adding are already retained (and not autoreleased).
    – Hot Licks
    Dec 21, 2011 at 13:38
  • Without seeing more of your code, Im not sure I can help you. Dec 21, 2011 at 13:57

3 Answers 3

0

I have ran into instances where addObject leaks and simply replacing that line with insertObject:atIndex fixes it. I even proved it by running several leaks tests.

Now, can I give you an exact reason of why it leaks and when? Not really... I can take a guess and say that the latter is more precise. I definitely know it fixed my issue and just classified it as a bug :)

0

Impossible to tell without more code. But, addObject: will retain what you pass it. So you can consider that the array “owns” the object, and you can release it after calling your addContentsObject: method.

And as Hot Licks mentioned, if nobody every releases the array, all the objects it owns will hang around as well.

What you may want to do with the Leaks instrument is look at one of your leaked objects, and see all the references.

Oh, and you may want to consider switching to ARC.

-1

I'm pretty sure it has to do with the way Obj-C looks at method names. Anything prefixed with -copy -add or -new will add a retain count to your returned object. If you don't intend it to be this way, try renaming the method once and see if it still leaks. My guess is it won't.

1
  • The name of the method doesn't affect how it works. (The name is used by the Analyze command.) Dec 21, 2011 at 17:53

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.