类扩展(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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值