ios 从 nsdictionary 中删除键/值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19791506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 02:45:33  来源:igfitidea点击:

Remove keys/values from nsdictionary

ioscore-data

提问by BluGeni

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.

我正在尝试将我的 coredata 转换为 json,我一直在努力让它工作,但已经找到了一种几乎可以工作的方法。

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.

这很好用,除非我将 NSIndexSet 保存在一些核心数据属性中。这给 JSON 写入带来了问题。现在,我的索引集不需要转换为 json,所以我想知道是否有办法从 dict 中删除所有索引?或者也许有更好的方法来做到这一点我不知道。

here is part of the nslog of dict:

这是 dict 的 nslog 的一部分:

...
    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)

所以在这种情况下,我想从 dict 中删除“wiring1”,但需要能够以“动态”的方式进行(不使用名称“wiring1”来删除它)

回答by Ruslan Soldatenko

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

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

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

对于动态删除值,从 dict 中获取所有键,测试每个键的对象并删除不必要的对象:

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.

注意:删除值不适用于快速枚举。作为替代的快速黑客,您可以创建一个没有不必要对象的新字典。

回答by Kisel Alexander

Use NSMutableDictionary instead NSDictionary.Your code will looks like:

使用 NSMutableDictionary 代替 NSDictionary。您的代码将如下所示:

NSMutableDictionary *dict = [[self.form dictionaryWithValuesForKeys:keys] mutableCopy]; //create dict
[dict removeObjectForKey:@"wiring1"]; //remove object

Don't forget use mutableCopy.

不要忘记使用 mutableCopy。

回答by jrturton

This sample code will pass through an NSDictionaryand build a new NSMutableDictionarycontaining only JSON-safe properties.

此示例代码将通过NSDictionary并构建一个NSMutableDictionary仅包含 JSON 安全属性的新属性。

At the moment it does not work recursively, e.g. if your dictionary contains a dictionary or array, it will drop it rather than pass through the dictionary itself and fix that, but that is simple enough to add.

目前它不能递归地工作,例如,如果你的字典包含一个字典或数组,它会删除它而不是通过字典本身并修复它,但这很容易添加。

// Note: does not work recursively, e.g. if the dictionary contains an array or dictionary it will be dropped.
NSArray *allowableClasses = @[[NSString class], [NSNumber class], [NSDate class], [NSNull class]];
NSDictionary *properties = @{@"a":@"hello",@"B":[[NSIndexSet alloc] init]};
NSMutableDictionary *safeProperties = [[NSMutableDictionary alloc] init];

[properties enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop){
    BOOL allowable = NO;
    for (Class allowableClass in allowableClasses)          {
        if ([obj isKindOfClass:allowableClass])
        {
            allowable = YES;
            break;
        }
    }       
    if (allowable)
    {
        safeProperties[key] = obj;
    }
}];
NSLog(@"unsafe: %@, safe: %@",properties,safeProperties);