从nsdictionary中删除键/值

我试图将我的coredata转换为json,我一直在努力使这个工作,但已经find了一个几乎工作的方式。

我的代码:

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

也是“forms”是:

  @property (strong, retain) NSManagedObject *form; 

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

这里是dict的nslog的一部分:

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

所以在这种情况下,我想从字典中删除“布线1”,但需要能够以“dynamic”的方式(不使用名称“布线1”来删除它)

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

为了dynamic删除值,从字典中获取所有的键,testing每个键的对象并删除不必要的对象:

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

注意:删除值不适用于快速枚举。 作为另一种快速入侵,你可以创build一个新的字典,而不必要的对象。

使用NSMutableDictionary代替NSDictionary.Your代码将如下所示:

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

不要忘记使用mutableCopy。

这个示例代码将通过一个NSDictionary并build立一个新的NSMutableDictionary只包含JSON安全属性。

目前它不能recursion工作,例如,如果你的字典包含一个字典或数组,它将会放弃它,而不是通过字典本身并修复它,但是这足够简单的添加。

 // Note: does not work recursively, eg 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);