从 nsdictionary 中删除键/值



我正在尝试将我的核心数据转换为 json,我一直在努力让它工作,但找到了一种几乎有效的方法。

我的代码:

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

"形式"也是:

 @property (strong, retain) NSManagedObject *form;

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

以下是字典的NSlog的一部分:

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

所以在这种情况下,我想从字典中删除"wirering1",但需要能够以"动态"方式执行此操作(不使用名称"wirering1"来删除它)

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

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

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

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

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

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

不要忘记使用mutableCopy。

此示例代码将传递一个NSDictionary并生成仅包含 JSON 安全属性的新NSMutableDictionary

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

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

最新更新