In Objective-C, why can a class extension add instance variables, but a class class cannot?

I know that we cannot add instance variables to the class category, but we can add to the continuation class, can someone tell me why or give me some details about this. I know that we can use the associated element in a category, I want to know that implementation details lead to this. Many thanks.

+4
source share
2 answers

TL; DR

Class extensions only modify the classes you own, while categories can modify any existing class.

ivars ( iOS OSX 64-bit), .

, .


(, clang ), , - .

Apple

, , ( ). , , @implementation , , , , Cocoa Cocoa , NSString.

: (, , ).

@interface , - , .

ivar . :

@interface MyClass : NSObject {
    NSInteger a;
    NSInteger b;
}
@end

@interface MyClass : NSObject {
    NSInteger a;
}
@end

@interface MyClass() {
    NSInteger b;
}
@end

( .m, b ).

, .

, , , Objective-C ivars.

? , ivars , , .

ivar , , NSObject () Framework, - .

, , , .

ivar iOS (iPhone OS ) 64- OSX ivars, Objective-C , 32- Mac.


http://www.sealiesoftware.com/blog/archive/2009/01/27/objc_explain_Non-fragile_ivars.html http://www.cocoawithlove.com/2010/03/dynamic-ivars-solving-fragile-base.html

+6

, class extension .

@interface SimpleClass : NSObject
@property int someProperty;
@end

@interface Foo()
@property float aNewProperty; // added through class extension 
@end

PS: Objective-C. Objective-C , . - Abstract Protected Objective-C? ? Objective-C .

-1

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


All Articles