我想重写在超类中声明的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
发布于 2013-06-16 03:34:11
只有超类才能访问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;
}
如果没有值,则不会更新值。它只是根据需要返回一个默认值。
发布于 2018-04-10 20:30:05
要访问超类变量,必须将它们标记为@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
https://stackoverflow.com/questions/17127056
复制相似问题