Memory management iOS


#1

Hi, in the 3rd edition of this book, page 87 we read:“All this automatic clean-up and memory recycling occurs simply by setting items to nil. That’s the power of ARC.” This relates to following code:

[code]  // create array
    NSMutableArray *items = [[NSMutableArray alloc] init];  
    
    // add random BNRItems to the array
    for (int i = 0; i < 10; i++) {
        BNRItem *p = [BNRItem randomItem];  
        [items addObject:p];  
    }
    
    // print items in array
    for (BNRItem *item in items) {
        NSLog(@"%@", item);
    }
    
    NSLog(@"Setting items to nil...");

    items = nil;[/code]

My question is, say I am using ARC, and I don’t set items = nil as above. Do I have memory leak?
I tested and dealloc seems to be properly called on all BNRItems anyway.


#2

If there are no other (strong) references to it, you don’t need to set it to nil. The ARC will see that there are no other references to it and will automatically release it.


#3

Perhaps I am wrong, but I am assuming you tested by commenting out or removing the line that sets items to nil, running the program, and seeing that the output “Destroyed…” lines still get printed. If this is the case, I believe what is happening is that when the main function exits, the local item variable from main loses its owner, and this then results (in this case) as though you had explicitly set items to nil.

i.e., I believe that these lines are being printed after the main function exits, and that the application is then performing its final clean-up and releasing any items back to the heap that have lost their owner. That is, I think there is some “behind the scenes” clean-up that still happens after the main function exits, but before the program finally has completed.


#4

I think I was slightly wrong in my earlier reply. I think that, if the line to set “items” to nil is removed or commented out, the “items” array will lose its owner when the “return 0” statement at the end of main is reached. This is because the curly brackets that enclose all of the code within main ABOVE the “return 0” statement (i.e,. the curly brackets that being at the end of the “@autoreleasepool” line) defines the scope of the “items” variable. The variable is declared within these brackets, so loses its scope as soon as the ending curly bracket before the “return 0” is exited.