類擴展(class extension)

OC裏面類擴展類似protected和private的作用。

1.類擴展是一種特殊的類別,在定義的時候不需要加名字。下面代碼定義了類Things的擴展。

@interface Things ()

{

    NSInteger thing4;

}

@end

2.類擴展作用

1)可以把暴露給外面的可讀屬性改爲讀寫方便類內部修改。

公有可讀、私有可寫的屬性(Publicly-Readable, Privately-Writeable Properties)

在.h文件裏面聲明thing2爲只讀屬性,這樣外面就不可以改變thing2的值。

1
2
3
4
5
6
7
@interface Things : NSObject
 
@property (readonly, assign) NSInteger thing2;
 
- (void)resetAllValues;
 
@end

 在.m裏面resetAllValues方法實現中可以改變thing2爲300.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章