Property attributes: strong, weak, copy, assign — when to use which?
Ownership
- strong — a strong reference; the object lives while the property points to it. Default for object types under ARC. For everything the object owns.
- weak — weak, automatically zeroed on the target's dealloc. For
delegate,dataSource, back-references to a parent — to avoid a cycle. Only for objects that support weak references. - copy — the setter calls
copyand stores a snapshot. Mandatory for types with a mutable subclass:NSString,NSArray,NSDictionary,NSSet,NSData— otherwise someone can pass anNSMutableStringand change it later. For blockscopymoves the block from the stack to the heap (under ARCstrongdoes the same, butcopyis the documented convention). - assign — plain assignment without retain. For scalars:
NSInteger,CGFloat,BOOL, enums, structs. For objects it equalsunsafe_unretained— a dangling pointer after dealloc, practically unused. - unsafe_unretained — the explicit variant of assign for objects.
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep