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。

相关文章:

  • 2022-12-23
  • 2022-02-15
  • 2021-09-17
  • 2022-12-23
  • 2022-12-23
  • 2021-07-29
  • 2022-12-23
猜你喜欢
  • 2021-07-13
  • 2022-12-23
  • 2021-07-19
  • 2022-12-23
  • 2021-07-07
  • 2021-05-12
相关资源
相似解决方案