Search code examples
iosmemory-managementcopyretain

iOS and memory management


Possible Duplicate:
Difference between retain and copy?

I'm learning iOS development right now and I don't understand the memory management very well, I have read the guide Advanced Memory Management Programming Guide in the apple develop center, but still have questions. The most important question I want to know is: What's the difference between copy and retain when define a property of a class? Thank you!


Solution

  • There are a thousand answers to this on SO! However, the first thing to understand is that when you define a @property you are issuing a directive to the compiler of your application and the retain/copy (and all the other things you see in the brackets) are instructions to the compiler on how to follow the directive.

    @property essentially means - Please Mr. Compiler, make me some accessor methods (getters & setters).

    So, retain & copy are instructions to the compiler which tell it how to operate inside those getter / setter accessors.

    copy means - when I say [myClass setMyProperty:propertyReference] - I want the class to make a copy of the property. A complete new instance of the property. Therefore the copy inside the class is not affected by external shenanigans going on outside of the class.

    retain means - I want the class to remember the exact instance of the property I am setting. NOT a new instance at all. In this case, when that instance changes, your class will know the up to date state of the property.