1.//首先通过runtime的class_copyPropertyList与property_getName函数实现Model对象属性转字符串的功能
-(NSArray *)propertiesToString:(NSObject*)objc
{
u_int count;
objc_property_t *properties =class_copyPropertyList([objc class], &count);
NSMutableArray *propertiesArray = [NSMutableArray arrayWithCapacity:count];
for (int i = 0; i
{
const char* propertyName =property_getName(properties[i]);
[propertiesArray addObject: [NSString stringWithUTF8String: propertyName]];
}
free(properties);
NSLog(@"%@",propertiesArray);
return propertiesArray;
}
2.//通过KVC键值编码来实现从服务器获取JSON数据后自动给Model对象赋值
-(BOOL)analysisData:(NSObject *)objcModel data:(NSData *)data
{
NSError *error;
NSArray * arrayProperties = [self propertiesToString:objcModel];
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if(error != nil)
{
NSLog(@"%@",error.description);
return false;
}
for(int i=0;i
{
//通过KVC键值编码给Model赋值
[objcModel setValue:[dict objectForKey:arrayProperties[i]] forKey:arrayProperties[i]];
}
return true;
}