关联
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];
}
修改对象指针
object_setClass(object, [modifyClass class]);
方法交换(Method Swizzling)
Method firstMethod = class_getInstanceMethod(class, firstSEL);
Method secondMethod = class_getInstanceMethod(class, secondSEL);
method_exchangeImplementations(firstMethod, secondMethod);
发送消息
objc_msgSend(testObject,@selector(methodWithString:),@"objc_msgSend");
//根据sel_registerName返回一个方法 == SEL
objc_msgSend(testObject,sel_registerName("methodWithString:"),@"sel_registerName");
获取协议列表
+ (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];
}