当一个模型有很多属性,给定的需求需要获取所有的属性的时候,如果一个一个写,效率很低,这个时候就可以用class_copyIvarList解决了。
例如有这样一个类:
#import
@interface Model : NSObject
@property(nonatomic,copy)NSString *name;
@property(nonatomic,copy)NSString *sex;
@property(nonatomic,copy)NSString *idno;
@property(nonatomic,copy)NSString *address;
@property(nonatomic,copy)NSString *mobile;
+(instancetype)modelWithValues:(NSArray *)values;
@end
现在需要获取他的以key=value的形式打印其所有属性及其值。就可以这样写了:
-(NSString )description{
unsigned int count=0;
Ivar list=class_copyIvarList([self class], &count);
NSMutableArray resultArray=[NSMutableArray array];
for(int i=0;i<count;i++){
Ivar var=list[i];
NSString varName=[NSString stringWithUTF8String:ivar_getName(var)];
//去掉前面的下划线
NSString *tmp=[varName substringFromIndex:1];
SEL method=NSSelectorFromString(tmp);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
id value=[self performSelector:method];
#pragma clang diagnostic pop
if(!value||value==NULL){
value=@"";
}
NSString *item=[NSString stringWithFormat:@"%@=%@",tmp,value];
[resultArray addObject:item];
}
free(list);
return [resultArray componentsJoinedByString:@"&"];
}