Effects of releasing newEntry objects?


#1

Hello,

I am in the section of Chapter 4 on memory leaks. We’re told to release the object after it’s added to the array:

[array addObject];
[newEntry release];

I guess I’m confused - since arrays store pointers to objects instead of copies of the objects, don’t we need to retain the objects themselves as long as the array? Else, wouldn’t the array point to blocks of freed memory? Will this have long term effects?

Thanks!


#2

When an object is added to a collection object, the object becomes owned also by the collection object. If another owner of the object relinquishes its ownership, the collection object still owns the object.

It is important that you understand how object ownership is managed. Therefore, you should read Programming with Objective-C: developer.apple.com/library/mac … ction.html


#3

Ah OK. So let me see if I have this right.

  1. So object is created, retain count is 1.
  2. Pointer to object is added to array, retain count is 2.
  3. Object is then released, retain count is 1.

Now when the array is released, the retain count is zeroed out and it can be deallocated. This must be the reason why console output prints all the object descriptions in the array, THEN all the deallocation logs. Thanks for your help!