0
What happens if you add your just created object to a mutable array, and you release your object?

Open 1 Answers 29 Views Technology

What happens if you add your just created object to a mutable array, and you release your object?

1 Answer

0

It depends. If you owned the object before adding it to the array, you still must release your own ownership claim to avoid a leak — the array’s ownership claim on the object is separate, and does nothing to absolve you of your own responsibility with respect to the memory management rules.

Object *obj = [[Object alloc] init];

[anArray addObject:obj];

[obj release];

On the other hand, if you did not own the object, then you still don’t own it after you add it to the array, and still must not release it. The array does establish its own ownership claim, but just like your own code, it’s responsible for balancing its own claims.

Object *obj = [Object object];

[anArray addObject:obj];

// or, avoiding a temp variable

[anArray addObject:[Object object]];

by (251k points)
...