从子类中的超类覆盖属性

时间:2013-06-15 19:16:15

标签: ios objective-c

我想覆盖在超类中声明的NSString属性。当我尝试使用默认的ivar(使用与属性相同的名称但使用下划线)时,它不会被识别为变量名。它看起来像这样......

超类的接口(我没有在这个类中实现getter或setter):

//Animal.h
@interface Animal : NSObject

@property (strong, nonatomic) NSString *species;

@end

子类中的实现:

//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

2 个答案:

答案 0 :(得分:10)

只有超类才能访问ivar _species。您的子类应如下所示:

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

    return [super species];
}

如果当前未设置该值,则将其设置为默认值。另一种选择是:

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

    return result;
}

如果没有值,则不会更新该值。它只是根据需要返回默认值。

答案 1 :(得分:0)

要访问超类变量,必须将它们标记为@protected,访问此类变量只会在类及其继承人内部

@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