从子类中的超类覆盖属性
我想覆盖在超类中声明的NSString属性。 当我尝试使用默认的伊娃,它使用与属性相同的名称,但使用下划线,它不会被识别为variables名称。 它看起来像这样…
超类的接口(我没有在这个类中实现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
只有_species
访问ivar _species
。 你的子类应该是这样的:
- (NSString *)species { NSString *value = [super species]; if (!value) { self.species = @"Homo sapiens"; } return [super species]; }
如果当前没有设置该值,则将该值设置为默认值。 另一种select是:
- (NSString *)species { NSString *result = [super species]; if (!result) { result = @"Home sapiens"; } return result; }
如果没有值,则不更新该值。 它只是根据需要返回一个默认值。