Objective-C:覆盖超类getter并尝试访问ivar时的编译器错误 [英] Objective-C: Compiler error when overriding a superclass getter and trying to access ivar

查看:107
本文介绍了Objective-C:覆盖超类getter并尝试访问ivar时的编译器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个iOS 6应用程序。

I'm working on building an iOS 6 app.

我有一个类 TDBeam ,它继承自超类 TDWeapon

I have a class TDBeam which inherits from superclass TDWeapon.

超类 TDWeapon 在TDWeapon.h文件中声明@property:

The superclass TDWeapon declares a @property in the TDWeapon.h file:

@interface TDWeapon : UIView

@property (nonatomic) int damage;

@end

我没有明确地@synthesize属性,因为我让Xcode自动这样做。

I do not explicitly @synthesize the property, as I'm letting Xcode automatically do so.

在子类 TDBeam 中,我覆盖了TDBeam.m文件中的getter:

In the subclass TDBeam I override the getter in the TDBeam.m file:

#import "TDBeam.h"

@implementation TDBeam

- (int)damage {
    return _damage;
}

@end

Xcode自动完成getter方法名称,如预期的那样。但是当我尝试引用_damage实例变量(继承自超类)时,我得到一个编译器错误:

Xcode auto-completes the getter method name, as expected. But when I attempt to reference the _damage instance variable (inherited from the superclass), I get a compiler error:

Use of undeclared identifier '_damage'

我在这里做错了什么?我已经尝试显式添加@synthesize,并更改_damage ivar的名称,但编译器不会看到它或来自超类的任何其他ivars。我认为ivars是可见的并且可以从子类访问?

What am I doing wrong here? I've tried explicitly adding @synthesize, and changing the name of the _damage ivar, but the compiler doesn't "see" it or any other ivars from the superclass. I thought ivars were visible and accessible from subclasses?

推荐答案

合成的ivars 对子类可见,是明确还是自动创建: @的可见性是什么?合成实例变量?由于它们在实现文件中有效声明,因此它们的声明不包含在包含子类的翻译单元中。

Synthesized ivars are not visible to subclasses, whether they are explicitly or automatically created: What is the visibility of @synthesized instance variables? Since they are effectively declared in the implementation file, their declaration isn't included in the "translation unit" that includes the subclass.

如果你真的想直接访问那个ivar,你必须在子类可以看到它的地方显式地声明它(在它的默认受保护形式),例如私有头中超类的类扩展。

If you really want to access that ivar directly, you'll have to explicitly declare it (in its default "protected" form) somewhere that the subclass can see it, such as a class extension of the superclass in a private header.

这篇关于Objective-C:覆盖超类getter并尝试访问ivar时的编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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