I regularly use lazy loading to instantiate custom classes, arrays, etc. The pattern is typically:
@property (strong, nonatomic) Class *class;
...
- (Class *)class
{
if(!_class) _class = [[Class alloc]init];
return _class;
}
Is it possible to use the same pattern to configure UI elements? For example, instead of formatting all my buttons and views in ViewWillAppear, I would like to put the formatting in the getter. For example:
- (UIButton *)button
{
if(!_button) {
_button = [[UIButton alloc]init];
self.button.backgroundColor = [UIColor redColor];
}
return _button;
}
The problem is I am using a storyboard and XCode instantiates the button so asking if it is nill should always return false. So the background will never be changed. If I remove the if-then, then the background will be set every time the getter is accessed which is probably OK but not optimal.
So, how do I use a UI element’s getter to configure the element?
If this is really the way you want to do it, just use a
BOOLflag. For example: