IOS How can I dump multiple properties of an object into a dictionary using a predicate or KVC?

I have a class that has bloated with properties, and now there are about 30 of them, most of which are integer enumerated types.

My code currently uses this in several places, and I try to gently navigate the new dictionary view.

I want to create a dictionary from this object, but include only values ​​that are not 0 (values ​​that contain some data).

Is there some objective-c key value encoding mask that can help me simplify writing this method?

@property(nonatomic)kGrade grade;
@property(nonatomic)kQuality quality;
//a whole bunch more properties

    -(NSMutableDictionary*)itemAsDictionary
    {
        if(itemDictionary !=nil)
        {
            return itemDictionary;
        }else
        {
            itemDictionary = [[NSMutableDictionary alloc] initWithCapacity:40];


            //I really dont want to write a whole bunch of such statements
            if(self.grade>0)
            {
                [itemDictionary setObject:@(self.grade) forKey:@"grade"];
            }
            //add 39 other items

        }
        return itemDictionary;
    }
+4
source share
2
- (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;
}

, , . .

: , [self class] , , [Item class].

- , 0 -nil-, . , , .

+1

dictionaryWithValuesForKeys:, , :

- (NSMutableDictionary *)itemAsDictionary {
    NSArray *keyArray = @[@"grade",
                          @"otherProperty"
                          // etc.
                          ];

    NSMutableDictionary *itemDictionary = [[self dictionaryWithValuesForKeys:keyArray] mutableCopy];

    NSArray *keys = [itemDictionary allKeys];

    for(NSString *key in keys) {
        NSNumber *item = itemDictionary[key];
        if(item.doubleValue == 0.0)
            [itemDictionary removeObjectForKey:key];
    }

    return itemDictionary;
}
+2

All Articles