Overriding property getters with lazy loading in Objective-C

纵饮孤独 提交于 2019-12-05 07:09:24

You might want to declare _infoImageView as a protected variable in the header file alongside with the property. Another idea is to create a public defaultImageView method to call inside the lazy getter. Something like this:

@interface MyGenericClass : UIViewController
@property (nonatomic, readonly) UIImageView *infoImageView

...

@implementation GenericClass

- (UIImageView *)infoImageView
{
    if (!_infoImageView) {
        _infoImageView = [self defaultImageView];
    }
    return _infoImageView;
}

- (UIImageView *)defaultImageView
{
    return [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"PlaceholderInfoImage"]];
}

...

@interface MySpecificSubclass : MyGenericClass

...

@implementation MySpecificSubclass

- (UIImageView *)defaultImageView
{
    return [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"SpecialInfoImage"]];
}

You could use the technique that UIViewController uses for its view:

- (UIView *)view{
    if(!_view){
        [self loadView];
        NSAssert(_view, @"View must be set at end of loadView");
    }
    return _view;
}

- (void)loadView{
    // subclasses must set self.view in their override of this.
    NSAssert(NO, @"To be overridden by subclass");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!