Anandh Anandh - 8 months ago 68
iOS Question

Objective C - Assign, Copy, Retain

I'm new to Objective C. I have basic knowledge in C, including the concept of pointers. I have two basic questions:

  1. Can someone explain the difference between assign,copy, and retain with some analogy?

  2. How do you handle a function which returns pointer variable, and how do you perform messaging through a return pointer?


Updated Answer for Changed Documentation

The information is now spread across several guides in the documentation. Here's a list of required reading:

The answer to this question now depends entirely on whether you're using an ARC-managed application (the modern default for new projects) or forcing manual memory management.

Assign vs. Weak - Use assign to set a property's pointer to the address of the object without retaining it or otherwise curating it; use weak to have the property point to nil automatically if the object assigned to it is deallocated. In most cases you'll want to use weak so you're not trying to access a deallocated object (illegal access of a memory address - "EXC_BAD_ACCESS") if you don't perform proper cleanup.

Retain vs. Copy - Declared properties use retain by default (so you can simply omit it altogether) and will manage the object's reference count automatically whether another object is assigned to the property or it's set to nil; Use copy to automatically send the newly-assigned object a -copy message (which will create a copy of the passed object and assign that copy to the property instead - useful (even required) in some situations where the assigned object might be modified after being set as a property of some other object (which would mean that modification/mutation would apply to the property as well).