(1)将类的实现分散到多个不同文件或多个不同框架中。
(2)创建对私有方法的前向引用。
(3)向对象添加非正式协议。
@interface MyClass : NSObject
- (float)value;
@end
@interface MyClass () { //注意此处:扩展
float value;
}
- (void)setValue:(float)newValue;
@end
@implementation MyClass
- (float)value {
return value;
}
- (void)setValue:(float)newValue {
value = newValue;
}
@end
我们推荐在自定义类的.m文件中使用扩展,这样就能保证良好的代码封装性,避免把私有接口暴露给外面。从而达到了封装私有方法的目的。
再者,对第一条 利用类别分散实现
举例代码:
头文件CatagoryThing.h包含类的声明和一些类别,导入Foundation框架,然后带有3个整型变量的声明
类声明之后是3个类别,每个类别具有一个实例变量的访问器,将这些实现分散到不同的文件中#import<Foundation/Foundation.h> @interface CategoryThing : NSObject { int thing1; int thing2; int thing3; } @end // CategoryThing
类别可以访问其继承的类的实例变量,类别的方法具有最高的优先级- (void) setThing1: (int) thing1; - (int) thing1; @end // CategoryThing (Thing1) @interface CategoryThing (Thing2) - (void) setThing2: (int) thing2; - (int) thing2; @end // CategoryThing (Thing2) @interface CategoryThing (Thing3) - (void) setThing3: (int) thing3; - (int) thing3; @end // CategoryThing (Thing3)
类别可以分散到不同文件中,甚至不同框架中
504



被折叠的 条评论
为什么被折叠?



