Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
799 views
in Technique[技术] by (71.8m points)

objective c - Are synthesized instance variables generated as private instead of protected?

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.

For example, if I write:

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

and in the .m

@implementation MyFirstClass
@synthesize size;
@end

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...