您的位置:首页 > 移动开发 > IOS开发

iOS类别(Category)和扩展(Extension,匿名类)

2015-07-13 15:00 281 查看
Category在iOS在开发常用。

特别是对于系统扩展上课时间。我们不能继承系统类。直接添加到系统类方法,最大程度上体现Objective-C动态语言特征。

#import
@interface NSObject (Category)
- (void)myMethod;
@end


这是一个最简单的Category,作用于NSObject类。给NSObject加入了一个方法。

使用Category须要注意的点:

(1) Category的方法不一定非要在@implementation中实现。也能够在其它位置实现,可是当调用Category的方法时,根据继承树没有找到该方法的实现,程序则会崩溃。

(2) Category理论上不能加入变量,可是能够使用@dynamic 来弥补这样的不足。

#import
static const void * externVariableKey =&externVariableKey;
@implementation NSObject (Category)
@dynamic variable。
- (id) variable
{
return objc_getAssociatedObject(self, externVariableKey);
}
- (void)setVariable:(id) variable
{
objc_setAssociatedObject(self, externVariableKey, variable, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


-----------------------------------------------------------

Extension很像是没有命名的类别,即匿名类别

@interface MyClass : NSObject
@property (retain, readonly) float value;
@end
//一般的时候。Extension都是放在.m文件里@implementation的上方。
@interface MyClass ()
@property (retain, readwrite) float value;
@end


使用Extension须要注意的点:

(1) Extension中的方法必须在@implementation中实现,否则编译会报错。

两者有一点差别



图片摘自: http://blog.sina.com.cn/s/blog_a2c098b50101gsn0.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: