Search code examples
objective-ciospropertiesinstance-variables

Objective-C: Compiler error when overriding a superclass getter and trying to access ivar


I'm working on building an iOS 6 app.

I have a class TDBeam which inherits from superclass TDWeapon.

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

@interface TDWeapon : UIView

@property (nonatomic) int damage;

@end

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

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

#import "TDBeam.h"

@implementation TDBeam

- (int)damage {
    return _damage;
}

@end

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'

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?


Solution

  • 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.

    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.