Why are my objects being deallocated?


Hi all,

So from my understanding from this chapter:

Using someObject = nil;

Will destroy that object, as it looses an owner and any objects it points to will also be destroyed - This is ARC at work, and I get that.

In the chapter it goes on to explain the @autorelease and any object inside the curley brackets gets deallocated once it looses an owner, automotically. Cool, I understand that too.

What puzzles me is this code


#import <Foundation/Foundation.h>
#import “BNRItem.h”

int main(int argc, const char * argv[])

    BNRItem *backPack = [[BNRItem alloc]init];
    [backPack setItemName:@ "Backpack"];
    BNRItem *calculator = [[BNRItem alloc]init];
    [calculator setItemName:@ "Calculator"];

[backPack setContainedItem:calculator];
NSLog (@ “%@”, backPack);
NSLog (@ “%@”, calculator);

return 0;



Output is:

2012-11-07 15:19:37.400 RandomPossessions[61706:303] Backpack ( ): Worth R0, recorded on 2012-11-07 13:19:37 +0000 2012-11-07 15:19:37.404 RandomPossessions[61706:303] Calculator ( ): Worth R0, recorded on 2012-11-07 13:19:37 +0000 2012-11-07 15:19:37.408 RandomPossessions[61706:303] Deallocation: Backpack ( ): Worth R0, recorded on 2012-11-07 13:19:37 +0000 2012-11-07 15:19:37.409 RandomPossessions[61706:303] Deallocation: Calculator ( ): Worth R0, recorded on 2012-11-07 13:19:37 +0000

I have not set these items to nil and they are not inside an autorelease - so why are they getting deallocated? (How do they loose their owners? )

Obviously changing container to have a strong reference stops this - but that is a retain cycle.

Any help?

Thanks all!


As I read in the book, autorelease is for object pointers obtained without using alloc or copy. If an object is created using alloc, you get a strong reference on that object and it will be deleted only when the reference does not exist anymore. If the object is obtained without alloc, ARC executes autorelease call behind the scene, placing an object to the auto deletion pool at the end of autorelease loop.

The code you are referring to (cited from the book) is dealing with alloc objects. Autorelease pool has no effect on them and they are deleted when the referencing variable goes out the scope, i.e. at the end of main().


Ah, okay that clears it up a lot.

Appreciate the reply! :smiley: