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

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(selfexternVariableKey);

}

- (void)setVariable:(id) variable

{

    objc_setAssociatedObject(selfexternVariableKeyvariable, 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值