movePossessionAtIndex using ARC question


in this code:

Possession *p = [allPossessions objectAtIndex:from]; [allPossessions removeObjectAtIndex: from]; [allPossessions insertObject:p atIndex:to];

  1. the first statement creates a pointer “p” to point to the 5th index(lets just say) of allPossessions
  2. now you are going to remove the 5th index from allPossessions? Where does “p” point to now? I know that the book says to retain “p” but it is not allowed using ARC.
  3. how are we going to insert an object that doesnt point to anything? Assuming that #2 is correct?

thanks for the clarification. …


Just like instance variables, local variables are also strong references unless otherwise specified.

So when we say

we are creating a strong local reference to whatever object is at the appropriate index in the array. At this moment there are two strong references to the posssession, keeping it alive.

Then, we can tell the array to

with impunity. Our pointer, p, is a strong reference to the aforementioned object. Don’t forget that under ARC, as long as there is at least one valid strong reference to an object, the object will continue to exist in memory.

Now that the array has forgotten about the object, our local p pointer is the only reference keeping the object from deallocating.

Finally, we can

which tell the array to remember the object again. Now there are once again two strong references to the object, not just the one we created, but one inside the array as well.

We can now let our local pointer p fall out of scope (which destroys the pointer), leaving the array as the only thing with a valid strong reference to said object.

Now consider what would happen if we left out the first line: if we removed the object from the array without creating a strong local reference to it first, then the number of strong references to the object would go from 1 to 0, instead of 2 to 1. When the number of strong references hits zero, the object would deallocate immediately. Then we would be in for some hurt when we hit the third line.


thanks so much for the help and confirmation. that explains a lot and will come in handy as i traverse for the rest of the book. :slight_smile: