objective-c 中 category 和 extension 的区别

apple官方文档说extension是 匿名category,从形式上extension确实是不具名的category,但事实上差别很大。category就不细说,主要是期待subclass,为现有类动态添加新的方法。而引入extension的目的主要是Publicly-Readable, Privately-Writeable Properties,即实现外部只读,内部可写。如下所示,

// .h
@interface MyClass : NSObject
@property (readonly, retain) NSString* myString;
@end

// .m
@interface MyClass ()
@property (readwrite, retain) NSString* myString;
@end

因此,extension 和 category 的不同主要有,

1. 形式上来看extension是匿名的category。

2. extension里边声明的方法必须在main implementation实现,类似于protocol里的@required。而category则声明的方法没有强制实现的要求。

3. extension 和 category 都不能定义新的实例变量。但extension可以定义新的property,然后在main implementation里@synthesize 新的property。而category定义新的property却不能@synthesize,这时可以使用Associative References技术实现对新定义的property的getter和setter。