Category在iOS在开发常用。
这是一个最简单的Category,作用于NSObject类。给NSObject加入了一个方法。
使用Extension须要注意的点:
(1) Extension中的方法必须在@implementation中实现,否则编译会报错。
特别是对于系统扩展上课时间。我们不能继承系统类。直接添加到系统类方法,最大程度上体现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
版权声明:本文博客原创文章。博客,未经同意,不得转载。