3

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?

2
  • Not sure if just a typo but you will need an NSMutableArray for the second array Commented Jul 11, 2011 at 0:08
  • This, I fear, is a less-than-desirable strategy. You really should be filtering array1 against a predicate. See +[NSPredicate predicateWithBlock:] and -[NSArray filteredArrayUsingPredicate:]. An added benefit of this clearer approach is that you don't have to think so hard about memory management! :) Commented Jul 11, 2011 at 1:45

1 Answer 1

5

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]).

Sign up to request clarification or add additional context in comments.

1 Comment

Sending a message to a dellocated object is undefined behavior. It might blow your program up, or it might make it look like the object is still alive with a valid retain count even though it isn't, or it might send dirty email to your boss. (The former two are more likely, though.)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.