Search code examples
iosobjective-cios5propertiesautomatic-ref-counting

Objective-C ARC: strong vs retain and weak vs assign


There are two new memory management attributes for properties introduced by ARC, strong and weak.

Apart from copy, which is obviously something completely different, are there any differences between strong vs retain and weak vs assign?

From my understanding, the only difference here is that weak will assign nil to the pointer, while assign won't, which means the program will crash when I send a message to the pointer once it's been released. But if I use weak, this won't ever happen, because message send to nil won't do anything.

I don't know about any differences between strong and retain.

Is there any reason why should I use assign and retain in new projects, or are the kind of being deprecated?


Solution

  • From the Transitioning to ARC Release Notes (the example in the section on property attributes).

    // The following declaration is a synonym for: @property(retain) MyClass *myObject;
    
    @property(strong) MyClass *myObject;
    

    So strong is the same as retain in a property declaration.

    For ARC projects I would use strong instead of retain, I would use assign for C primitive properties and weak for weak references to Objective-C objects.