Obj C:不能在子类中从父类继承公共属性 [英] Obj C: Can't inherit public property from parent class in child class

查看:40
本文介绍了Obj C:不能在子类中从父类继承公共属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Objective-C中练习继承,这是我的Person父类

I am practicing inheritance in Objective-C and this is my Person parent class

// This is Person.h
@interface Person : NSObject

@property(nonatomic, strong) NSNumber *age;
@property(nonatomic, strong) NSString *race;

-(instancetype)init;
-(instancetype)initWithAge:(NSNumber*)age andRace:(NSString*)race;

@end

这就是我在学生班上要做的事情

This is what I'm trying to do in my Student class

// This is Student.h
#import "Person.h"

@interface Student : Person

@property(nonatomic, strong) NSString *classification;
@property(nonatomic, strong) NSString *major;

@end

// This is Student.m
#import "Student.h"
#import "Person.h"

@implementation Student

-(instancetype)init
{   
    return [self initWithClassification:@"Freshman" andMajor:@"Computer Science"
                                 andAge:[[NSNumber alloc] initWithInt:20] andRace:@"Caucasian"];
}

-(instancetype)initWithClassification:(NSString*)classification andMajor:(NSString*)major
                               andAge:(NSNumber*)age andRace:(NSString*)race
{
    self = [super init];

if (self)
{
    _classification = classification;
    _major = major;
    _age = age;
    _race = race;
}

return self;
}

@end

编译器不喜欢我的行为_age = 年龄;_race = 种族;

The compiler is not liking my doing _age = age; _race = race;

使用未声明的标识符 _age 是指年龄吗?有人能告诉我我哪里出错了吗?谢谢.

Use of undeclared identifier _age did you mean age? Can someone tell me where I went wrong? Thank you.

推荐答案

当你声明一个这样的属性时,clang 会自动为你@synthesize 它(即它会创建一个 getter 和 setter),但合成属性对子类不可见,您有不同的选择来使其工作.

When you declare a property like that, clang will automatically @synthesize it for you (i.e it will create a getter and setter), but synthesized properties are not visible to subclasses, you have different alternatives to make it working.

可以在子类的接口中合成ivar

You can synthesize the ivar in the interface of the subclass

@synthesize age = _age;

或者您可以在超类的接口上声明受保护的 ivar,以便在子类上可见.

Or you can declare the ivar protected on the interface of the superclass, so that will be visible on the subclasses.

@interface Person : NSObject {
    @protected NSNumber *_age;
}

或者你可以在你的子类上使用 self.age = ... ,而根本不使用 ivar.

Or you can use self.age = ... on your subclass, without using the ivar at all.

这篇关于Obj C:不能在子类中从父类继承公共属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆