Synthesized instance variables created as private rather than protected?

Since recent times in iOS, we can define the properties that accessors will generate for instance variables. From what I understand, it is not necessary to declare an instance variable, as it will be automatically made for us.

For example, if I write:

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

and in .m

 @implementation MyFirstClass @synthesize size; @end 

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

The problem is that when creating the second class MySecondClass, which is a subclass of MyFirstClass, it seems that I cannot access the size of the instance variable in this subclass:

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

Are automatically created instance variables private? Is it possible to set them as protected so that I can access them in subclasses? I know that it is possible to declare an instance variable yourself, but I'm just wondering ...

With a superclass like this, it works: (Is it because it is explicitly declared as protected?)

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

Thanks for the help! Nicolas.

+4
source share
2 answers

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

The reason for this is that there is usually only one class for the implementation file, which means that the compiler does not know about the instance variable when compiling other classes. If you have several classes in one file, the compiler might know about it, but you are still not allowed to redefine the scope. Possible reasons in this case may be consistent, or simply so that the compiler does not have to look for instance variables in many places.

+3
source

Using:

 self.size = 10; 

This will be displayed in the setSize method.

0
source

Source: https://habr.com/ru/post/1395981/


All Articles