在Objective-C中使用延迟加载覆盖属性获取器 [英] Overriding property getters with lazy loading in Objective-C

查看:75
本文介绍了在Objective-C中使用延迟加载覆盖属性获取器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常会像这样在自己的getter方法中实例化@property对象:

I usually lazy instantiate my @property objects in their getter methods like this:

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

@implementation GenericClass

- (UIImageView *)infoImageView
{
    if (!_infoImageView) {
        _infoImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"PlaceholderInfoImage"]];
    }
    return _infoImageView;
}

但是当进行子类化时,我经常想重写某些@properties使其更具体地属于子类.所以我想更改实例并做类似的事情:

But when subclassing, I would often like to override some of the @properties to be more subclass specific. So I'd like to change the instantiation and do something like:

@interface MySpecificSubclass : MyGenericClass
//...

@implementation MySpecificSubclass

- (UIImageView *)infoImageView
{
    if (!_infoImageView) {
        _infoImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"SpecialInfoImage"]];
    }
    return _infoImageView;
}

但这是不可能的,因为子类无法访问_infoImageView iVar.

But that's not possible, because the subclass can't access the _infoImageView iVar.

我要做的是不良风格吗? 还是为此有一个通用的解决方案/最佳实践?我看到的唯一解决方案是将iVar公开,这就像在违反封装原则...

Is what I'm trying to do bad style? Or is there a common solution / best practice for this? The only solution I see is to make the iVar public, which feels like violating encapsulation principles...

感觉这是一个非常基本的问题,必须已经有数百万个答案,但是搜索了几个小时之后,我只能找到

It feels like this is such a very basic question, that there must be millions of answers already out there, but after searching for hours all I could find was Objective-C: Compiler error when overriding a superclass getter and trying to access ivar , but it provides no solution.

推荐答案

您可能希望将_infoImageView声明为头文件中的受保护变量,并带有该属性. 另一个想法是创建一个公共的defaultImageView方法来在惰性getter内部进行调用. 像这样:

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"]];
}

这篇关于在Objective-C中使用延迟加载覆盖属性获取器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆