• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Objective-C基础8:类扩展(classextension)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

封装的特性就是暴露公共接口给外边调用,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;
}

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++和Objective-C混编(官方文档翻译)发布时间:2022-07-12
下一篇:
iphone开发Objective-C新特性──类别与协议(转)发布时间:2022-07-12
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap