Clarifications on Lottery.app memory management


#1

I am working through the chapter on memory management and have a burning question.

According to the authors, with ARC off we need to release the following objects:
— newEntry objects
— weekComponents objects
— array object

Why don’t we need to release the iWeeksFromNow objects and the cal object?

Interestingly, adding [cal release] just before the end of the programme does not crash it, which I understand as proof that cal was indeed lingering in the memory (but because of its small and predictable size cannot cause an application crash, therefore may be safely left in memory until the program exits).

However, adding the [iWeeksFromNow release] instruction in the loop DOES crash the programme (bad access exception). Which means that iWeeksFromNow is “automatically” deallocated and indeed should not be manually released.

So—how come? What’s going on

Thank you!

UPDATE: Actually, releasing the cal object also leads to an exception throw.


#2

… And as an addendum to my question, how can we monitor the retain count of objects during a debugging session? Would that be at all meaningful anyway? I read in the Apple documentation that using po [myObject retainCount] is not a reliable debugging strategy.


#3

I skipped that chapter, so I can’t answer specifically about those objects. But in general I find it easiest to find leaks using static analysis and Instruments.
Static analysis is amazing but not perfect, I’ve seen some cases where it though things were being leaked and they were not.
Also, when doing old school memory management, it is very very valuable to “Enable Zombie Objects” (shown at the end of Chapter 5).


#4

Thanks, fgiraffe, I will take a closer look at these tools.

Still a burning curiosity to know why the iWeeksFromNow objects need not (and as it appears, should not) be released in the example!

Perhaps one of the authors could chime in? I’d be grateful.


#5

Unforgivable mistake on my part as I have even diligently studied Aaron’s Objective-C book,which covers this in the section “Retain Count Rules”).

I now understand that I only own objects created by methods containing the words “copy,” “alloc,” or “new.” Such objects I indeed need to release manually (assuming ARC is off).

In this example, I own neither iWeeksFromNow nor cal. Both are owned by their respective classes and placed in the autorelease pool.

My mistake was therefore that the objects were over-released: once by the autorelease pool and once manually by me.