Pregunta

I was under the impression that class extensions in Objective C were just anonymous categories. However, you may add properties to these class extensions, which is impossible in categories, so I'm a bit confused:

#import "Money.h"

@interface Money ()
@property(nonatomic) NSUInteger amount;
@end

@implementation Money

@end

How are class extensions implemented? As categories? Then why are you allowed to add iVars to it? When are class extensions added to the class, in compile time or when the class is loaded?

¿Fue útil?

Solución

Class extensions are a compiler mechanism that allows offsetting a subset of the instance variables, declared properties and methods declared in @interface to a specific translation unit (e.g., from a public header file to an implementation file), thus allowing header files to declare only what is supposed to be public. From the runtime perspective, extensions do not exist: everything that is declared in a class extension is merged onto the principal class. This implies that extensions must be compiled along its principal class (as opposed to categories), which you can infer from the fact that you have a single @implementation for both the principal class and its extension. It’s all part of the same class.

As you can see, class extensions are quite different from categories. Categories cannot declare instance variables, categories can reside in implementation files different from the one that implements the principal class (including classes declared and implemented in libraries) and they have their own @implementation. Furthermore, categories are explicitly loaded and attached to the principal class by the runtime.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top