rid
rid

Reputation: 63442

Passing Objective-C objects from NSArray to NSArray

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

Answers (1)

Dan Rosenstark
Dan Rosenstark

Reputation: 69757

Assuming the non-conformant objects are not being retained elsewhere, your assumption is correct with the following caveats:

  1. 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.

  2. Also note that array2 must be a NSMutableArray instance, otherwise you cannot call addObject:.

  3. 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

Related Questions