Are synthesized instance variables generated as pr

2019-01-25 20:21发布

问题:

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.