Managing memory in RandomPossessions.m


#1

On page 53, we add this code to RandomPossessions.m

[items release]; items = nil;

Since we have already created an AutoRelease pool, wouldn’t we get the same result by adding:

…after we allocate items? What are the advantages of following the book’s method?

Thanks,
Jack


#2

There are two differences:

The first is that in the original block of code, we release the object pointed to by items and we also set the variable items to point at nil. Therefore, the NSMutableArray that items used to point at is gone and you can’t accidentally access that memory later by referencing the items pointer. (Of course, in this application, there really isn’t a “later”)

The second difference is that by sending an object release, you immediately release it. If its retain count is one, it is immediately deallocated. If you autorelease it, the release of the object is delayed. In this simple command line application, it doesn’t matter, there is nothing else happening. But in an iPhone application, this might matter, especially in low memory conditions.

The rule is that if you don’t need an object any more, you release it on the spot. You only use autorelease if you have ownership of an object that you are giving away - usually, because you are creating this object yourself and returning it to the caller. By autoreleasing an object you could have released, you delay the inevitable and add complexity to debugging a retain count problem later.


#3

Thanks for the clear and thorough explanation. So as I understand it, the two approaches are pretty much equivalent in this particular example, simply because it’s so short, and nothing happens between [items release]; and [pool drain];

Now I see that the real difference becomes apparent when these statements are part of a larger app. I have to say, this forum adds a lot of value to an already excellent book.

Thanks,
Jack