Default property attributes with ARCMay 4, 2015 · 2 minute read
Should you bother specifying the default values of the Objective-C @property declaration? For example, since the introduction of ARC the following two statements are equivalent:
@property NSArray *name; @property (strong, atomic, readwrite) NSArray *name;
The following defaults apply to the first declaration:
- For memory management a
strongreference is the default over
retainis a synonym of
- For thread safety
atomicis the default over
- For mutability
readwriteis the default over
Some confusion arises because it easy to forget that
strong has been the default for object types since the introduction of ARC. Previously the default was
assign and there is still some old documentation from Apple that has not caught up. As a result I still tend to find myself writing the following:
@property (strong) NSArray *name;
or perhaps more typically:
@property (strong, nonatomic) NSArray *name;
I prefer the more explicit statement of the memory management model even though I know many people consider it wasted typing. There is a case for saying that is has been long enough and developers should know the defaults. I have considered dropping it from the code I share on this site but in the end I keep it for a couple of reasons:
- Developers new to the platform may not be aware of the implications when relying on a default. Making it explicit makes it more likely they will consider the correct choice.
- As Swift gains adoption in the coming years we all might need an explicit reminder of what memory management semantics apply when switching back to legacy Objective-C code.
You may disagree and prefer the more compact style by omitting defaults and that is fine. Whatever you decide applying a consistent style guide is a good idea.