Category是Objective-C中常用的語法特性,通過它可以很方便的為已有的類來添加函數。但是Category不允許為已有的類添加新的屬性或者成員變量。
一種常見的辦法是通過runtime.h中objc_getAssociatedObject / objc_setAssociatedObject來訪問和生成關聯對象。通過這種方法來模擬生成屬性。
//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; - (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命令)或者運行時獲得對象的各種信息。