ios – 从nsdictionary中删除键/值

前端之家收集整理的这篇文章主要介绍了ios – 从nsdictionary中删除键/值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试将我的coredata转换为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;

除了我在某些coredata属性中保存了NSIndexSet之外,这个工作正常.这给JSON写入带来了问题.现在,我的索引集不需要转换为json所以我想知道是否有办法从dict中删除所有索引?或者有更好的方法来做到这一点,我不知道.

这是dlog的nslog的一部分:

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

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

解决方法

为了能够删除值,您的字典必须是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]];
   }
}

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

猜你在找的iOS相关文章