3

我想覆盖在超类中声明的 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
4

2 回答 2

12

只有超类可以访问 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;
}

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

于 2013-06-15T19:34:11.427 回答
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
于 2018-04-10T12:30:05.390 回答