關(guān)聯(lián)
static const char LJKey = '\0';
objc_setAssociatedObject(self, &LJKey, header, OBJC_ASSOCIATION_ASSIGN);
objc_getAssociatedObject(self, &LJKey);
獲取類名
+ (NSString *)xx_getClassName:(Class)class {
const char *className = class_getName(class);
return [NSString stringWithUTF8String:className];
}
獲取屬性列表(公有和私有)
+ (NSArray *)xx_getPropertyList:(Class)class {
unsigned int count = 0;
objc_property_t *propertyList = class_copyPropertyList(class, &count);
NSMutableArray *list = [NSMutableArray arrayWithCapacity:count];
for (unsigned int i = 0; i < count; i++ ) {
const char *propertyName = property_getName(propertyList[i]);
[list addObject:[NSString stringWithUTF8String: propertyName]];
}
free(propertyList);
return [NSArray arrayWithArray:list];
}
獲取成員變量
+ (NSArray *)xx_getIvarList:(Class)class {
unsigned int count = 0;
Ivar *ivarList = class_copyIvarList(class, &count);
NSMutableArray *list = [NSMutableArray arrayWithCapacity:count];
for (unsigned int i = 0; i < count; i++ ) {
NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:2];
const char *ivarName = ivar_getName(ivarList[i]);
const char *ivarType = ivar_getTypeEncoding(ivarList[i]);
dic[@"ivarType"] = [NSString stringWithUTF8String:ivarType];
dic[@"ivarName"] = [NSString stringWithUTF8String:ivarName];
[list addObject:dic];
}
free(ivarList);
return [NSArray arrayWithArray:list];
}
修改對(duì)象指針
object_setClass(object, [modifyClass class]);
方法交換(Method Swizzling)
Method firstMethod = class_getInstanceMethod(class, firstSEL);
Method secondMethod = class_getInstanceMethod(class, secondSEL);
method_exchangeImplementations(firstMethod, secondMethod);
發(fā)送消息
objc_msgSend(testObject,@selector(methodWithString:),@"objc_msgSend");
//根據(jù)sel_registerName返回一個(gè)方法 == SEL
objc_msgSend(testObject,sel_registerName("methodWithString:"),@"sel_registerName");
獲取協(xié)議列表
+ (NSArray *)xx_getProtocolList:(Class)class {
unsigned int count = 0;
__unsafe_unretained Protocol **protocolList = class_copyProtocolList(class, &count);
NSMutableArray *list = [NSMutableArray arrayWithCapacity:count];
for (unsigned int i = 0; i < count; i++ ) {
const char *protocolName = protocol_getName(protocolList[i]);
[list addObject:[NSString stringWithUTF8String: protocolName]];
}
return [NSArray arrayWithArray:list];
}