Skip to content

Instantly share code, notes, and snippets.

@Tricertops
Last active December 15, 2015 05:49
Show Gist options
  • Save Tricertops/5212010 to your computer and use it in GitHub Desktop.
Save Tricertops/5212010 to your computer and use it in GitHub Desktop.
// How do you implement lazy loading getters?
- (NSString *)title {
if ( ! self->_title) {
NSString *string = @"lazy loaded";
// Do some real stuff here...
self->_title = string;
}
return self->_title;
}
// What about this?
- (NSString *)title LAZY(_title) {
NSString *string = @"lazy loaded";
// Do some real stuff here...
return string;
}
// The `LAZY` macro:
#define LAZY(IVAR) {\
if ( ! self->IVAR) {\
self->IVAR = [self lazyLoad##IVAR];\
}\
return self->IVAR;\
}\
\
- (NSString *)lazyLoad##IVAR
// After expansion:
- (NSString *)title {
if ( ! self->_title) {
self->_title = [self lazyLoad_title];
}
return self->_title;
}
- (NSString *)lazyLoad_title {
NSString *string = @"lazy loaded";
// Do some real stuff here...
return string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment