- 在
<objc/runtime.h>
中,我们通过Class
的结构体内容,可以看到ivars
指针指向包含了类中成员变量的结构体,通过它可以得到类中定义的成员变量,而Objective-C
中提供了相应的API方法。 - 相应的API方法为
Ivar *class_copyIvarList(Class cls, unsigned int *outCount)
。
// <objc/runtime.h>内
struct objc_class {
Class isa OBJC_ISA_AVAILABILITY;
#if !__OBJC2__
Class super_class OBJC2_UNAVAILABLE;
const char *name OBJC2_UNAVAILABLE;
long version OBJC2_UNAVAILABLE;
long info OBJC2_UNAVAILABLE;
long instance_size OBJC2_UNAVAILABLE;
struct objc_ivar_list *ivars OBJC2_UNAVAILABLE;
struct objc_method_list **methodLists OBJC2_UNAVAILABLE;
struct objc_cache *cache OBJC2_UNAVAILABLE;
struct objc_protocol_list *protocols OBJC2_UNAVAILABLE;
#endif
} OBJC2_UNAVAILABLE;
使用代码示例如下:
// DictToModel.h
#import <Foundation/Foundation.h>
@interface DictToModel : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *gender;
+ (instancetype)modelWithDictionary:(NSDictionary *)dictionary;
@end
// DictToModel.m
#import "DictToModel.h"
#import <objc/message.h>
@implementation DictToModel
+ (instancetype)modelWithDictionary:(NSDictionary *)dictionary{
id model = [[self alloc] init];
unsigned int count = 0;
Ivar *ivars = class_copyIvarList(self, &count);
// count:属性个数 ivars:属性指针数组
for (int i = 0 ; i < count; i++) {
Ivar ivar = ivars[i];
NSString *ivarName = [NSString stringWithUTF8String:ivar_getName(ivar)];
//这里注意,拿到的成员变量名(ivarName)为_name,_gender,因此需要截取字符串获得真正的成员变量名
ivarName = [ivarName substringFromIndex:1];
id value = dictionary[ivarName];
[model setValue:value forKeyPath:ivarName];
}
return model;
}
// 调用示例:
DictToModel *model = [DictToModel modelWithDictionary:@{@"name":@"wang",@"gender":@"man"}];
NSLog(@"%@",model.name); // wang
// 获取系统类的key值
+ (void)load{
unsigned int count = 0;
Ivar *ivars = class_copyIvarList(self, &count);
// count:属性个数 ivars:属性指针数组
NSMutableArray *array = [NSMutableArray array];
for (int i = 0 ; i < count; i++) {
Ivar ivar = ivars[i];
NSString *ivarName = [NSString stringWithUTF8String:ivar_getName(ivar)];
//这里注意,拿到的成员变量名(ivarName)为_name,_gender,因此需要截取字符串获得真正的成员变量名
ivarName = [ivarName substringFromIndex:1];
[array addObject:ivarName];
}
NSLog(@"%@",array);
}