Are synthesized instance variables generated as private instead of protected?

谁都会走 提交于 2019-11-28 01:26:15

问题


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.


回答1:


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.




回答2:


Use:

self.size = 10;

That will map to setSize method.



来源:https://stackoverflow.com/questions/9244745/are-synthesized-instance-variables-generated-as-private-instead-of-protected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!