- (NSMutableDictionary *)itemAsDictionary
{
NSMutableDictionary *resultDic = [[NSMutableDictionary alloc] init];
unsigned int outCount, i;
//type the name of the class you want to turn to dictionary
objc_property_t *properties = class_copyPropertyList([Item class], &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
const char *propName = property_getName(property);
if (propName) {
NSString *propertyName = [NSString stringWithUTF8String:propName];
id propertyValue = [self valueForKey:propertyName];
//set up the filter here
if([propertyValue isKindOfClass:[NSNumber class]] && [propertyValue intValue] > 0)
{
[resultDic setObject:propertyValue forKey:propertyName];
}else if(![propertyValue isKindOfClass:[NSNumber class]] && propertyValue !=nil)
{
//copy all non-nil variables
[resultDic setObject:propertyValue forKey:propertyName];
}
}
}
free(properties);
return resultDic;
}
I try to get the property list from a class and then return a dictionary, it's worked.maybe you can try it.
Edit: The code above did not work if I used [self class] in a subclass, but did work when I replaced self with [Item class].
I added a couple simple checks - I'm interested in numbers greater than 0 and non-nil properties, like strings and images. Notice that if I remove the second number check, the code will put zeros in the resulting dictionary.