Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove keys/values from nsdictionary

Tags:

ios

core-data

I am trying to convert my coredata to json, I have been struggling to get this to work but have found a way that is almost working.

my code:

NSArray *keys = [[[self.form entity] attributesByName] allKeys];
        NSDictionary *dict = [self.form dictionaryWithValuesForKeys:keys];
        NSLog(@"dict::%@",dict);

        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
                                                           options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                             error:&error];

        if (! jsonData) {
            NSLog(@"Got an error: %@", error);
        } else {
            NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            NSLog(@"json::%@",jsonString);
        }

also "form" is:

 @property (strong, retain) NSManagedObject *form;

This works fine except I have NSIndexSet saved in some of the coredata attributes. This poses a problem with the JSON write. Now, my indexsets do not need to be converted to json so I was wondering if there was a way to delete all indexes from the dict? or maybe there is a better way to do this I am unaware of.

here is part of the nslog of dict:

...
    whereExtent = "";
    wiring =     (
    );
    wiring1 = "<NSIndexSet: 0x82b0600>(no indexes)";
    wiringUpdated = "<null>";
    yardFenceTrees = "<null>";
}

so in this case I want to remove "wiring1" from dict but need to be able to do it in a "dynamic" way (not using the name "wiring1" to remove it)

like image 572
BluGeni Avatar asked Nov 05 '13 14:11

BluGeni


1 Answers

To be able to delete values, your dictionary must be an instance of NSMutableDictionary class.

For dynamically removing values, get all keys from dict, test the object of each key and remove unnecessary objects:

NSArray *keys = [dict allKeys];
for (int i = 0 ; i < [keys count]; i++)
 {
   if ([dict[keys[i]] isKindOfClass:[NSIndexSet class]])
   {
     [dict removeObjectForKey:keys[i]];
   }
}

Note: Removing values does not work with fast enumeration. As an alternative fast hack, you may create a new dictionary without unnecessary objects.

like image 180
Ruslan Soldatenko Avatar answered Nov 10 '22 23:11

Ruslan Soldatenko