The last fragment has the same effect as the first published.
As an improvement, while there is no operator in Objective-C such as ||= , you can omit the second parameter of the triple if statement and do
return _myArray = _myArray ?: [NSArray array];
which is exactly equivalent
return _myArray = _myArray ? _myArray : [NSArray array];
This is a language extension supported by modern versions of gcc and clang .
Bonus: if you want to save a few more keystrokes, you can do
- (NSArray *)myArray { return _myArray = _myArray ?: @[]; }
As a side note, skipping the middle operand may also be useful.
For example, in this case
id x = [self someMethod] ? [self someMethod] : [self anotherMethod];
if someMethod evaluates to true , it will be called twice, whereas
id x = [self someMethod] ?: [self anotherMethod];
it will be called only once.
source share