As is known that in ObjC property declared in .h file is the interface "visible outside", while property declared in .m file (class extension) can be only accessed in .m, kind of "private" or "hidden". But in practice code as follows can be compiled.
ClassA.h
@interface ClassA : NSObject
+ (void)foo;
@end
ClassA.m
#import "ClassA.h"
@interface ClassA ()
@property (nonatomic) NSInteger aInt;
@end
@implementation ClassA
+ (void)foo {
ClassA *aObj = [ClassA new];
aObj.aInt = 2; //?
}
@end
@interface _ClassB : NSObject //Some private class defined in the same .m file...
@end
@implementation _ClassB
+ (void)bar {
ClassA* aObj = [ClassA new];
aObj.aInt = 2; //?
}
@end
The fact is, not only ClassA *aObj
defined in ClassA
's own method can access class extension property aInt
, but ClassA *aObj
defined in another _ClassB
while in the same ClassA.m file can also access aInt
.
As far as I understand, aObj
defined in class method foo
has no difference with any ClassA *
type variable defined in another class and separate .m file. But by no means will the latter access 'aInt', say
ClassC.m
#import "ClassA.h"
...
- (void)fun {
ClassA *aObj = [ClassA new];
NSLog("%d", aObj.aInt); //Error! Property aInt not found on object of type 'ClassA*'
}
Why is this happening? Can this be explained with ObjC runtime mechanism or something?