Last Updated: February 25, 2016
·
725
· jarsen

Lazy Load with Style

Sometimes you might write a lazy-loading accessor for a @property that looks something like this:

- (NSMutableArray *)sections {
    if (!_sections) {
        _sections = [NSMutableArray new];
    }
    return _sections;
}

Try a more concise, and C-hackerish alternative:

- (NSMutableArray *)sections {
    return _sections = _sections ?: [NSMutableArray new];
}

This uses C's elusive ?: null coalescing operator, makes the assignment to the instance variable, and then returns _sections—all in one line.