Skip to content

Instantly share code, notes, and snippets.

@k0nserv
Last active August 29, 2015 13:56
Show Gist options
  • Save k0nserv/8984787 to your computer and use it in GitHub Desktop.
Save k0nserv/8984787 to your computer and use it in GitHub Desktop.
Lazy init. Initialize the value of a variable only when it's first needed
@interface MyClass()
// Lazy inits are perfect for readonly values
// Note that strong can be used instead of copy here because
// we control the creation of the array and don't have to worry about
// being passed a mutable version
@property(nonatomic, readonly, strong) NSArray *values;
@end
@implementation MyClass
// Always use explicit synthesize when overriding a getter or setter
@synthesize values = _values;
- (id)init {
self = [super init];
if (self) {
// The initializer is the other candidate for
// creating the _values array. The benefit of using a lazy
// init is that the value is only created if needed.
//_values = @[@1, @2, @3];
}
return self;
}
- (NSArray *)values {
if (!_values) { // Initialize only the first time and only if the property is needed
_values = @[@1, @2, @3];
}
return _values;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment