I’m still a tad confused on iPhone memory management. It’s not a huge issue as it doesn’t deal with the most common use cases (I just release in dealloc, and set to nil in viewDidUnLoad). But let’s get this straight:
Suppose I got an instance variable that is retained and synthesized. And I allocate it.
If I set it to nil, does that mean the object is deallocated in memory? It’s gone? Because someone told me setting it to nil only sets the pointer to nil, and doesn’t deallocate it from memory.
I know when the owner count is set to 0, the memory is deallocated.. That’s correct, right? If not, I think my entire universe may have been broken =)
When a piece of memory has a retain count of 0 associated with it, then it is available for reuse (so it is deallocated).
In your .h file:
In your .m file:
This statement does two things – firstly it allocates memory for “SomeObject” and in the process sets the retain count on that memory to 1. Secondly it assigns a pointer to that memory to the ivar via the synthesized setter method. The synthesized setter method calls release on any current memory pointed to by the iVar, which reduces its retain count by 1, and then assigns the pointer to the new object to the iVar and increments its retain count. Thus after this statement the retain count is 2
This sets the iVar via the synthesized setter method, which reduces the retain count of the current value by 1 and then sets the new value (nil) on the iVar. Thus in this example these two statements one after the other result in memory that still has a retain count of 1 and thus is not available for reuse by the operating system.
So if you allocate an object yourself and then also assign it to a retain property, then you should explicitly release it after assigning it to the retain property. (and in your dealloc method also release the ivar to cater for the property).
this allocates some memory (increasing its retain count to 1) then assigns a pointer to that memory to the iVar via the setter (increasing the retain count to 2) but also flags it for autorelease – which means it is added to the autorelease pool and released when your thread loses control (which will reduce the retain count by 1). Then when your object (self) is released, the dealloc method (if implemented properly) will release the ivar (myInstanceVariable) and then the retain count will go to 0 and the memory you originally allocated will be deallocated.