封裝的特性就是暴露公共接口給外邊調用,C++通過public定義公共方法提供給外面調用,protected和private定義的方法只能在類里面使用,外面不能調用,若外面調用,編譯器直接報錯,對於變量也同理。OC里面類擴展類似protected和private的作用。
1.類擴展是一種特殊的類別,在定義的時候不需要加名字。下面代碼定義了類Things的擴展。
@interface Things ()
{
NSInteger thing4;
}
@end
2.類擴展作用
1)可以把暴露給外面的可讀屬性改為讀寫方便類內部修改。
在.h文件里面聲明thing2為只讀屬性,這樣外面就不可以改變thing2的值。
@interface Things : NSObject @property (readonly, assign) NSInteger thing2; - (void)resetAllValues; @end
在.m里面resetAllValues方法實現中可以改變thing2為300.
@interface Things ()
{
NSInteger thing4;
}
@property (readwrite, assign) NSInteger thing2;
@end
@implementation Things
@synthesize thing2;
- (void)resetAllValues
{
self.thing2 = 300;
thing4 = 5;
}
2)可以添加任意私有實例變量。比如上面的例子Things擴展添加了NSInteger thing4;這個實例變量只能在Things內部訪問,外部無法訪問到,因此是私有的。
3)可以任意添加私有屬性。你可以在Things擴展中添加@property (assign) NSInteger thing3;
4)你可以添加私有方法。如下代碼在Things擴展中聲明了方法disInfo方法並在Things實現了它,在resetAllValues調用了disInfo
@interface Things ()
{
NSInteger thing4;
}
@property (readwrite, assign) NSInteger thing2;
@property (assign) NSInteger thing3;
- (void) disInfo;
@end
@implementation Things
@synthesize thing2;
@synthesize thing3;
- (void) disInfo
{
NSLog(@"disInfo");
}
- (void)resetAllValues
{
[self disInfo];
self.thing1 = 200;
self.thing2 = 300;
self.thing3 = 400;
thing4 = 5;
}
