1

just a short question: Does the NSMutableArray -addObject:(id)object method retain the object-parameter?

Thanks

Brian Webster
  • 30,033
  • 48
  • 152
  • 225
cschwarz
  • 1,195
  • 11
  • 24

4 Answers4

2

Yes, it will retain the object. The object will be released when the array is released. If you're adding objects you've allocated to the array, make sure you release them once they've been added.

Object *o = [[Object alloc]init];
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:o];
[o release];
[array release];
csano
  • 13,266
  • 2
  • 28
  • 45
2

Yes, anything in a collection (set, array, dictionary) will be retained in the collection. That is of course if the collection is retained at the first place.

Once you add anything in a collection you need to release it if you are the owner.

Desdenova
  • 5,326
  • 8
  • 37
  • 45
0

Yes. It also releases all the objects in contains when it's retain count reaches zero.

highlycaffeinated
  • 19,729
  • 9
  • 60
  • 91
0

The answer is, yes it does.

And in the future, here's how you can test for these situations. You can find out the retain count of an object using:

NSLog(@"Count: %d", [object retainCount]);

Use this code before and after adding the object to the array to see for yourself.

I must warn you though, a lot of people advise against using retainCount for anything. That being said, I think it's okay to use it to track increases and decreases in retaincounts for objects (like in my answer) but not much else.

Don't depend on retainCount values in your code; Just use the differences to track allocs and releases.

Sid
  • 9,508
  • 5
  • 39
  • 60
  • There are [good reasons **not** to use retainCount](http://stackoverflow.com/questions/4636146/when-to-use-retaincount)... – albertamg Jun 01 '11 at 17:07
  • Funny you mention that as I was just going to edit my answer regarding what you said. I agree that you can't use retaincount as an absolute value by itself, i.e., I wouldn't want to depend on it for my operations. I do believe that using retaincount to track if the retain count of an object increased, is useful after all. For example, like in my answer, using the retainCount call immediately before and after adding the object to the array, will, in fact, help in knowing if the retainCount was increased. It's there for a reason, after all :) – Sid Jun 01 '11 at 17:41