Trying to Understand ARC


I have been struggling for 2 days trying to understand the idea behind ARC compared to the old ways (release, retain, autorelease). For example, when I looked at the code just right above the figure 3.7, I still don’t understand why you only set nil to the items but not to the backpack and calculator. It seems to me that backpack and calculator still carry the pointer for the BNRIItem object. Wouldn’t that be a memory leak?


In the code before figure 3.7, it is still a work in progress to explain retain cycles. These objects are actually indestructible because of the retain cycle they create. Setting the backpack pointer to nil after fixing the retain cycle will destroy both of these objects. So right now, yes, this is a “memory leak”.

I think the part about ARC that deserves an explanation here is that you no longer have to send release, retain, etc., because they are done automatically. For example, in non-ARC code, if I was going to set a pointer to nil, I’d have to release it first:

[object release];
object = nil;

Since you always have to do this, ARC just says “well, if you set it to nil, I’ll release it for you.” So in ARC, this line is equivalent to the previous two lines:

object = nil;

Same thing goes for retain:

object = [anotherObject retain];
is the same as
object = anotherObject;


So what happens if I leave a method without setting an unused pointer to nil. In the example above, what if I just left out the

// what happens if I leave this out? // object = nil;

Would ARC do the right thing? Or do I have to be sure to set to nil all objects I no longer use? (sounds like it’s the latter). Thanks!


Depends if the object is an instance variable or a local variable. The book mentions it on page 66- if it’s an ivar, the pointer would be destroyed when the object that contains it is destroyed. If it’s a local variable, once the method is over, the stack frame is popped and the object that the pointer pointed to loses an owner.