Reputation: 63442
I have a NSArray
containing objects. I want to create a secondary NSArray
containing just some of the objects in the first NSArray
. I have something like:
[array1 enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if (something) {
[array2 addObject:obj]; // (1)
}
}];
[array1 release]; // (2)
I'm thinking that (1)
will increase the object's retainCount
(which will bring it from 1 to 2), then (2)
will decrease it (which will bring it from 2 to 1 for the objects added in array2
and from 1 to 0 for the objects that did not get added).
So I expect that, after doing this, it will be safe to access the objects from array2
, and the non-conformant objects that did not pass the test will be deallocated.
Is this correct?
Upvotes: 3
Views: 140
Reputation: 69757
Assuming the non-conformant objects are not being retained elsewhere, your assumption is correct with the following caveats:
Note that retainCount
is generally considered a tricky measure and it's better to talk about the problem is terms of whether array1
is retaining the non-conformant objects or not, without reference to retainCount
. The reason is that the retainCount
may be (and often is) different from what you expect.
Also note that array2 must be a NSMutableArray
instance, otherwise you cannot call addObject:
.
In 95% of cases (made up statistic), you should not use retain
and release
yourself, but should prefer using autorelease
(if the object is NARCed, new alloc retained or copied) or nothing at all if the object is already autoreleased (e.g., [NSMutableArray array]
).
Upvotes: 5