TestsTested | ✓ |
LangLanguage | Obj-CObjective C |
License | MIT |
ReleasedLast Release | Dec 2014 |
Maintained by Nicolas Goutaland.
One line lazy property definition, with auto triggering, custom selectors
ARC only, XCode 4.4 minimum (For auto synthesized properties)
Dealing with lazy properties can be cumbersome sometimes, copy/pasting same code again and again.
This code can be disturbing when reading source file.
Sometimes, you have to execute some code on property initialisation.
More information on lazy instanciation on Wikipedia
RootViewController.m
@interface DemoViewController ()
...
// Lazy properties
@property (nonatomic, strong) SimpleViewController *simpleViewController; // Will be used modally
@property (nonatomic, strong) DetailViewController *detailViewController; // Will be pushed from tableview
@end
@implementation DemoViewController
...
#pragma mark - UITableViewDelegate methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// No need to worry about detail view controller instantiation. It will be created at first call
// This allows you to keep your code super clear
[self.navigationController pushViewController:self.detailViewController
animated:YES];
}
#pragma mark - UIActions
- (IBAction)showModal:(id)sender
{
// No need to worry about view controller instantiation here too. It will be created at first call
// First configuration was moved to a dedicated method, auto triggered on object creation
[self presentViewController:self.simpleViewController
animated:YES
completion:nil];
}
#pragma mark - Configuration methods
// This method will be autotriggered when simpleViewController will be instantiated
- (void)configureSimpleViewController
{
// This methods will be called only once, so you can perform initial configuration here
_simpleViewController.backgroundColor = [UIColor redcolor];
}
// Magic happens here. Write macros at the end of the file, to keep it clean. Use property name
LAZY_PROPERTY(simpleViewController);
LAZY_PROPERTY(detailViewController);
@end
You will find more examples in provided sample, such as using custom selector.
Let me know if you have some other use cases
Only strong properties are supported. Lazy weak properties may instantiate a new instance at each call. atomic properties are not supported. When overriding atomic properties, you have to override getter and setter. Using LazyProperty on an atomic property will result in compiler a warning message.
Cocoapods: pod 'LazyProperty'
Manual: Copy the Classes folder in your project
Import header in your project. .pch is a good place ;)
#import "LazyProperty.h"
1.0 : Initial release 1.1 : Added some tests, triggered method can have a parameter, removed @synchronized from generated getter
Nicolas Goutaland