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
上面是頭文件聲明,下面的實(shí)現(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
這個(gè)和Category無關(guān)盈魁,但是也是runtime.h的一種應(yīng)用翔怎。DLIntrospection,是 一個(gè)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)試時(shí)(通過po命令)或者運(yùn)行時(shí)獲得對象的各種信息飘痛。