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.
Written by Jason Larsen
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ios
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#