Category是Objective-C中常用的語法特性,通過它可以很方便的為已有的類來添加函數(shù)。但是Category不允許為已有的類添加新的屬性或者成員變量。
一種常見的辦法是通過runtime.h中objc_getAssociatedObject / objc_setAssociatedObject來訪問和生成關(guān)聯(lián)對象。通過這種方法來模擬生成屬性。
//NSObject+IndieBandName.h
@interface NSObject (IndieBandName)
@property (nonatomic, strong) NSString *indieBandName;
@end
上面是頭文件聲明,下面的實現(xiàn)的.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無關(guān),但是也是runtime.h的一種應(yīng)用。DLIntrospection,是 一個NSObject Category。它為NSObject提供了一系列擴(kuò)展函數(shù):
@interface NSObject (DLIntrospection)
+ (NSArray *)classes;
+ (NSArray *)properties;
+ (NSArray *)instanceVariables;
+ (NSArray *)classMethods;
+ (NSArray *)instanceMethods;
+ (NSArray *)protocols;
+ (NSDictionary *)descriptionForProtocol:(Protocol *)proto;
+ (NSString *)parentClassHierarchy;
@end
通過這些函數(shù),你可以在調(diào)試時(通過po命令)或者運(yùn)行時獲得對象的各種信息。