您的位置:首页 > 其它

runtime 获取类的属性,方法,成员变量,以及协议 字典转model 总结

2016-05-19 20:40 495 查看
runtime 的使用笔记

1 runtime 获取类的属性,方法,成员变量,以及协议

unsigned int count;
//获取属性列表
objc_property_t *propertyList=class_copyPropertyList([model class], &count);
for (unsigned int i=0; i<count; i++) {
const char *propertyName=property_getName(propertyList[i]);
NSLog(@"propertyName----->%@",[NSString stringWithUTF8String:propertyName]);
NSLog(@"propertyValue----->%@",[model valueForKey:[NSString stringWithUTF8String:propertyName]]);
NSLog(@"propertyValueClass----->%@",[[model valueForKey:[NSString stringWithUTF8String:propertyName]] class]);
}
//获取方法列表
Method *methodList=class_copyMethodList([model class], &count);
for (unsigned int i=0; i<count; i++) {
Method method=(methodList[i]);
NSLog(@"method----->%@",NSStringFromSelector(method_getName(method)));
}
//获取成员变量列表
Ivar *ivarList=class_copyIvarList([model class], &count);
for (unsigned int i=0; i<count; i++) {
Ivar myIvar=ivarList[i];
const char *ivarName=ivar_getName(myIvar);
NSLog(@"Ivar----->%@",[NSString stringWithUTF8String:ivarName]);
}

//获取协议列表
__unsafe_unretained Protocol **protocolList=class_copyProtocolList([model class], &count);
for (unsigned int i=0; i<count; i++) {
Protocol *myProtocal=protocolList[i];
const char *protocolName=protocol_getName(myProtocal);
NSLog(@"protocol----->%@",[NSString stringWithUTF8String:protocolName]);
}


2 runtime 简单字典转model  自定义方法

model.h

@property (nonatomic ,copy)NSString *propertyA;
@property (nonatomic ,copy)NSString *propertyB;
@property (nonatomic ,copy)NSString *propertyC;

+ (instancetype)modelWithDictionary:(NSDictionary *)dictionary;

model.m

+ (instancetype)modelWithDictionary:(NSDictionary *)dictionary{
return [[self alloc]initWithDictionary:dictionary];
}

- (instancetype)initWithDictionary:(NSDictionary *)dictionary{
self = [super init];
if (self) {
unsigned int count;
//获取属性列表 遍历并赋值
objc_property_t *propertyList=class_copyPropertyList([self class], &count);
for (unsigned int i=0; i<count; i++) {
const char *propertyName=property_getName(propertyList[i]);
//属性名
NSString *propertyNameStr = [NSString stringWithUTF8String:propertyName];
NSString *propertyValue = [dictionary objectForKey:propertyNameStr];
if ([WYHTools isBlankString:propertyValue]) {
propertyValue = @"暂无";
}
[self setValue:propertyValue forKey:propertyNameStr];
}
}
return self;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息