让Category支持添加属性与成员变量

来源:互联网 发布:新红帆网络 编辑:程序博客网 时间:2024/06/05 06:06

Category是Objective-C中常用的语法特性,通过它可以很方便的为已有的类来添加函数。但是Category不允许为已有的类添加新的属性或者成员变量。     
一种常见的办法是通过runtime.h中objc_getAssociatedObject / objc_setAssociatedObject来访问和生成关联对象。通过这种方法来模拟生成属性。 AssociatedObject : 关联对象

//NSObject+IndieBandName.h@interface NSObject (IndieBandName)@property (nonatomic, strong) NSString *indieBandName;@end

上面是头文件声明,下面的实现的.m文件:

复制代码
// NSObject+IndieBandName.m    #import "NSObject+Extension.h"#import <objc/runtime.h>
static const void *IndieBandNameKey = &IndieBandNameKey;  
  @implementation NSObject (IndieBandName)
@dynamic indieBandName;

//synthesize会自动生成属性的setter,getter方法

//dynamic修饰时,settergetter方法会在程序运行时或者用其他方式动态绑定,以便让编译器通过编译,其主要作用就是用在NSManagerObject对象的属性声明.coredata框架会在程序运行时为此类属性生成gettersetter方法

- (NSString *)indieBandName { return objc_getAssociatedObject(self, IndieBandNameKey);}- (void)setIndieBandName:(NSString *)indieBandName{ objc_setAssociatedObject(self, IndieBandNameKey, indieBandName, OBJC_ASSOCIATION_RETAIN_NONATOMIC);}@end
复制代码




 DLIntrospection

这个和Category无关,但是也是runtime.h的一种应用。DLIntrospection,是 一个NSObject Category。它为NSObject提供了一系列扩展函数:  

复制代码
@interface NSObject (DLIntrospection)+ (NSArray *)classes;+ (NSArray *)properties;+ (NSArray *)instanceVariables;+ (NSArray *)classMethods;+ (NSArray *)instanceMethods;+ (NSArray *)protocols;+ (NSDictionary *)descriptionForProtocol:(Protocol *)proto;+ (NSString *)parentClassHierarchy;@end
复制代码

通过这些函数,你可以在调试时(通过po命令)或者运行时获得对象的各种信息。






0 0