iOS类别(Category)与扩展(Extension)-b

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中实现,否则编译会报错。

posted on 2016-06-16 17:25  🌞Bob  阅读(206)  评论(0编辑  收藏  举报

导航