iOS深度可变序列化字典/数组

4

一些JSON来自我的应用程序分解的本地文件:{"1":{"name":"My List","list":[]}}

我使用这个iOS 5.1代码将整个内容转换为一个我认为是深度可变字典,由于所使用的选项:

NSData *data = [[NSFileManager defaultManager] contentsAtPath:jSONFile];
NSMutableDictionary *mydict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error];

有了选项NSJSONReadingMutableContainers,我会认为子数组list会属于这个类别:"NSJSONReadingMutableContainers - 指定数组和字典被创建为可变对象。" 来自NSJSONSerialization Class Reference,但是当我尝试执行以下代码时:

NSMutableArray *myarray = [mydict objectForKey:@"1"] objectForKey:@"list"];
[myarray addObject:@"test"];

第二行执行时出现以下异常:

-[__NSArrayI addObject:]: unrecognized selector sent to instance 0x887e840

** 应用程序因未捕获的异常 'NSInvalidArgumentException' 而终止,原因:'-[__NSArrayI addObject:]: unrecognized selector sent to instance 0x887e840'

根据我的研究 (1, 2, 3),通常在试图添加对象的元素(字典/数组)不可变时会出现上述错误。此外,根据我的研究 (1, 2),在obj-c中似乎没有办法测试对象是否确实是可变的,这是有意设计的。

所以我的问题是,我怎样才能确保我的 jSON 结构在序列化后或立即序列化后确实是“深度”可变的?我知道我不能在 mydict 上使用 mutableCopy 函数,因为该函数是浅层的。希望有方向或解决方案。谢谢。

2个回答

2

我使用了一个基于NSDictionary类别的实现来进行可变深拷贝,并且效果非常好:

深度可变复制NSMutableDictionary

因此,在反序列化JSON后,您只需调用mutableDeepCopy即可。

这就是我的做法:

@interface NSDictionary(Category)
- (NSMutableDictionary *)mutableDeepCopy;
@end

@implementation NSDictionary(Category)
- (NSMutableDictionary *)mutableDeepCopy{
    NSMutableDictionary * ret = [[NSMutableDictionary alloc]
                             initWithCapacity:[self count]];

   NSMutableArray * array;

   for (NSString* key in [self allKeys]){

       if([[self objectForKey:key] respondsToSelector:@selector(mutableCopyWithZone:)]){
            array = [(NSArray *)[self objectForKey:key] mutableCopy];
           [ret setValue:array forKey:key];
       }
       else{
            [ret setValue:[self objectForKey:key] forKey:key];

       }
    }

    return ret;
}

@end

非常好。我不得不进行一些修改,因为我的字典包含包含数组的字典。 - Authman Apatira
@AuthmanApatira你可以发布一下你的代码,用于操作字典中的字典吗?谢谢! - Kyle Begeman

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接