从nsdictionary中删除键/值 [英] Remove keys/values from nsdictionary

查看:99
本文介绍了从nsdictionary中删除键/值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将我的coredata转换为json,我一直在努力让这个工作,但已经找到一种方法,几乎​​工作。

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.

我的代码:

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);
        }

也是form是:

 @property (strong, retain) NSManagedObject *form;

除了我在一些coredata属性中保存了NSIndexSet,这导致JSON写入的问题。现在,我的索引集不需要转换为json所以我想知道是否有一种方法来删除所有的索引从dict?或者有一个更好的方法来做到这一点我不知道。

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.

这里是dict的nslog的一部分:

here is part of the nslog of dict:

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

所以在这种情况下,我想从dict中删除wiring1能够以动态方式(不使用名称wiring1来删除它)。

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)

推荐答案

能够删除值,您的字典必须是 NSMutableDictionary 类的实例。

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

对于动态删除值, keys from dict,测试每个键的对象并删除不必要的对象:

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.

这篇关于从nsdictionary中删除键/值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆