I can’t figure out why class B can access class A private instance variable.
Here is my code
A.h
#import <Foundation/Foundation.h>
@interface A : NSObject
{
@private
int x;
}
@property int x;
-(void)printX;
@end
A.m
#import "A.h"
@implementation A
@synthesize x;
-(void)printX
{
NSLog(@"%i", x);
}
@end
B.h
#import "A.h"
@interface B : A
{
}
@end
main.m
B *tr = [[B alloc] init];
tr.x = 10;
[tr printX];
Here I can access instance variable of A class x despite it is declarated as private ?
You are not accessing the private variable there, at least not directly: you are accessing a public property, which has legitimate access to the private ivar.
Your code is equivalent to this:
The
@synthesizestatement created the getter and the setter methods for you. If you want only a getter to be available, mark your propertyreadonly, and do all writings through an ivar in theAclass.