我正在尝试将我的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]];
}
}
注意:删除值不适用于快速枚举.作为替代快速黑客,您可以创建一个没有不必要对象的新字典.