- (NSDictionary *)dictionaryRepresentation
{
NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary];
NSArray *propertyArray = [self getClassPropertys:[self class]];
for(NSString *key in propertyArray)
{
[mutableDict setValue:[self valueForKey:key] forKey:key];
}
return [NSDictionary dictionaryWithDictionary:mutableDict];
}
// 获取某个类自身的所有属性
- (NSArray *)getClassPropertys:(Class)classInstance
{
NSMutableArray *classPropertyDics = [[NSMutableArray alloc] init];
u_int count;
objc_property_t *properties = class_copyPropertyList(classInstance, &count);
for (int i = 0; i < count ; i++) {
const char* propertyName = property_getName(properties[i]);
const char* propertyAttributes = property_getAttributes(properties[i]);
NSString *name = [NSString stringWithUTF8String:propertyName];
NSString *attribute = [NSString stringWithUTF8String:propertyAttributes];
NSString *attributeType = [self parseAttributeType:attribute];
NSMutableDictionary *propertyDic = [[NSMutableDictionary alloc] init];
[propertyDic setObject:attributeType forKey:name];
[classPropertyDics insertObject:propertyDic atIndex:0];
// [classPropertyDics insertObject:name atIndex:0];
}
free(properties);
return (NSArray *)classPropertyDics;
}
- (NSString *)parseAttributeType:(NSString *)Attributes
{
NSRange leftRange = [Attributes rangeOfString:@"\""];
NSString *temp1 = [Attributes substringFromIndex:leftRange.location+1];
NSRange rightRange = [temp1 rangeOfString:@"\""];
NSString *temp2 = [temp1 substringToIndex:rightRange.location];
return temp2;
}
网友评论