iOS属性反射

iOS属性反射:就是将对象的所有属性,用动态的方式取出来,并根据属性名,自动绑值。


- (NSArray*)propertyKeys

{

unsignedintoutCount, i;

objc_property_t*properties =class_copyPropertyList([selfclass], &outCount);

NSMutableArray*keys = [[NSMutableArrayalloc]initWithCapacity:outCount];

for(i =0; i < outCount; i++) {

objc_property_t property = properties[i];

NSString*propertyName = [[NSStringalloc]initWithCString:property_getName(property)encoding:NSUTF8StringEncoding];

[keys addObject:propertyName];

}

free(properties);

returnkeys;

}

- (BOOL)reflectDataFromOtherObject:(NSObject*)dataSource

{

BOOLret =NO;

for(NSString*key in  [self propertyKeys]) {

if([dataSource  isKindOfClass:[NSDictionary class]]) {

ret = ([dataSource valueForKey:key]==nil)?NO:YES;

}

else{

ret = [dataSourcerespondsToSelector:NSSelectorFromString(key)];

}

if(ret) {

id propertyValue = [dataSource valueForKey:key];

//该值不为NSNULL,并且也不为nil

if(![propertyValue isKindOfClass:[NSNull class]] && propertyValue!=nil) {

[self setValue:propertyValue forKey:key];

}

}

}

returnret;

}

/////使用方法

NSDictionary*dicJsonData;

EntityObject*objValue;

[objValue  reflectDataFromOtherObject:dicJsonData];//这样就可以完成对象的自动赋值了,

你可能感兴趣的:(iOS属性反射)