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

iOS runtime 机制 通过别扩展category给一个类添加属性

2016-04-13 22:54 239 查看
http://www.cnblogs.com/tangbinblog/p/3944316.html

category使用
objc_setAssociatedObject/objc_getAssociatedObject 实现添加属性

属性 其实就是get/set 方法。我们可以使用 objc_setAssociatedObject/objc_getAssociatedObject 实现 动态向类中添加 方法

@interface NSObject (CategoryWithProperty)

@property (nonatomic, strong) NSObject *property;

@end

@implementation NSObject (CategoryWithProperty)

- (NSObject *)property {
return objc_getAssociatedObject(self, @selector(property));
}

- (void)setProperty:(NSObject *)value {
objc_setAssociatedObject(self, @selector(property), value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end


good.http://blog.sina.com.cn/s/blog_7ea0400d0101eyj6.html

苹果的官方文档

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://www.cocoachina.com/bbs/read.php?tid=126123
// Declaration

@interface MyObject (ExtendedProperties)

@property (nonatomic, strong, readwrite) id myCustomProperty;

@end

// Implementation

static void * MyObjectMyCustomPorpertyKey = (void *)@"MyObjectMyCustomPorpertyKey";

@implementation MyObject (ExtendedProperties)

- (id)myCustomProperty

{

return objc_getAssociatedObject(self, MyObjectMyCustomPorpertyKey);

}

- (void)setMyCustomProperty:(id)myCustomProperty

{

objc_setAssociatedObject(self, MyObjectMyCustomPorpertyKey, myCustomProperty, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: