综合实例变量是作为私有而不是作为保护生成的吗? [英] Are synthesized instance variables generated as private instead of protected?

查看:81
本文介绍了综合实例变量是作为私有而不是作为保护生成的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自从iOS上最近的运行时以来,我们就能够定义将为实例变量生成访问器的属性.据我了解,声明使用的实例变量不是强制性的,因为它将为我们自动完成.

Since recent runtimes in iOS, we are able to define properties that will generate accessors for instance variables. From what I understand, it is not mandatory to declare the instance variable used since it will be automatically done for us.

例如,如果我写:

@interface MyFirstClass
@property (readonly, nonatomic) int size; 
@end

和.m

@implementation MyFirstClass
@synthesize size;
@end

然后将为我添加一个名为"size"的实例变量,并将实现一个名为-(int)size"的方法.

Then an instance variable named "size" will be added for me and a method called "-(int)size" will be implemented.

问题是,当我创建第二个类MySecondClass(它是MyFirstClass的子类)时,似乎无法访问此子类中的实例变量大小:

The problem is that when I create a second class MySecondClass which is a subclass of MyFirstClass, it seems that I can't access the instance variable size within this subclass:

@interface MySecondClass : MyFirstClass
@end

@implementation MySecondClass
- (id)init {
    if (self = [super init]) {
        size = 10;  // this yields and error
    }
    return self;
}
@end

自动创建的实例变量是否私有?是否有可能将它们设置为受保护,以便我可以在子类中访问它们? 我知道可以自己声明实例变量,但是我只是想知道...

Are the automatically created instance variables private? Is there a possibility to set them as protected so I can access them in subclasses? I know there is the possibility to declare the instance variable myself, but I'm just wondering...

使用这样的超类可以工作:(是因为它被明确声明为受保护的吗?)

With a superclass like this it works: (Is it because it's expressly declared as protected?)

@interface MyFirstClass {
    int size;  // defined expressly and used as @protected
}
@property (readonly, nonatomic) int size;
@end

谢谢您的帮助! 尼古拉斯.

Thank you for your help!! Nicolas.

推荐答案

在主接口中未声明的任何实例变量都会自动为私有变量,并且不能覆盖此变量.如果在实现中定义实例变量时尝试使用范围修饰符,则会收到错误的说明,说明不一致.

Any instance variable not declared in the main interface is automatically private, and this cannot be overridden. If you try to use a scope modifier when defining instance variables in the implementation, you will get an error that the specification is inconsistent.

这样做的原因是每个实现文件通常只有一个类,这意味着编译器在编译其他类时不知道实例变量.如果同一文件中有多个类,则编译器可以知道它,但是仍然不允许覆盖该范围.在这种情况下,可能的原因可能是出于一致性考虑,或者只是这样,编译器不必在很多地方查找实例变量.

The reason for this is that there is usually only one class per implementation file, which means the compiler doesn't know about the instance variable when compiling other classes. If you have multiple classes in the same file, the compiler could know about it, but you still aren't allowed to override the scope. Possible reasons in this case could be for consistency, or just so the compiler doesn't have to look in so many places for instance variables.

这篇关于综合实例变量是作为私有而不是作为保护生成的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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