odd choice
odd choice

Reputation: 37

override property from superclass in subclass

I want to override an NSString property declared in a superclass. When I try to do it using the default ivar, which uses the the same name as the property but with an underscore, it's not recognised as a variable name. It looks something like this...

The interface of the superclass(I don't implement the getter or setter in this class):

//Animal.h
@interface Animal : NSObject

@property (strong, nonatomic) NSString *species;

@end

The implementation in the subclass:

//Human.m
@implementation

- (NSString *)species
{
    //This is what I want to work but it doesn't and I don't know why 
    if(!_species) _species = @"Homo sapiens";

    return _species;

}

@end

Upvotes: 3

Views: 10184

Answers (2)

Roman Solodyashkin
Roman Solodyashkin

Reputation: 829

to access the superclass variables, they must be marked as @protected, access to such variables will be only inside the class and its heirs

@interface ObjectA : NSObject
{
    @protected NSObject *_myProperty;
}
@property (nonatomic, strong, readonly) NSObject *myProperty;
@end

@interface ObjectB : ObjectA
@end

@implementation ObjectA
@synthesize myProperty = _myProperty;
@end

@implementation ObjectB
- (id)init
{
    self = [super init];
    if (self){
        _myProperty = [NSObject new];
    }
    return self;
}
@end

Upvotes: 1

rmaddy
rmaddy

Reputation: 318954

Only the superclass has access to the ivar _species. Your subclass should look like this:

- (NSString *)species {
    NSString *value = [super species];
    if (!value) {
        self.species = @"Homo sapiens";
    }

    return [super species];
}

That sets the value to a default if it isn't currently set at all. Another option would be:

- (NSString *)species {
    NSString *result = [super species];
    if (!result) {
        result = @"Home sapiens";
    }

    return result;
}

This doesn't update the value if there is no value. It simply returns a default as needed.

Upvotes: 13

Related Questions