NSJSONReadingMutableLeaves选项不起作用

时间:2013-10-13 13:39:16

标签: ios objective-c

NSDictionary *dict = @{@"key": @"value"};
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
NSError *error;
NSDictionary *dict1 = [NSJSONSerialization JSONObjectWithData:data  
    options:NSJSONReadingMutableLeaves  error:&error];
NSMutableString *ms =  [dict1 objectForKey:@"key"];
ms.string = @"ss";

我从上面的代码中得到了一个例外

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'尝试使用setString改变不可变对象:'

有什么问题?

1 个答案:

答案 0 :(得分:0)

我刚遇到这个问题,确实很烦人。

我开发了一个解决方法,在NSMutableArrayNSMutableDictionary上添加了两个,它们解析整个JSON树并用其可变相对替换每个叶子事件(如果它符合NSMutableCopying协议)。

以下是实施:

@implementation NSMutableArray (mutableLeavesAddition)

- (void)setLeavesMutable {
    for (int i=0; i<[self count]; i++) {
        NSObject *element = self[i];
        if ([element isKindOfClass:NSMutableDictionary.class] || [element isKindOfClass:NSMutableArray.class]) {
            [(NSMutableDictionary*)element setLeavesMutable];
        } else if ([element.class conformsToProtocol:@protocol(NSMutableCopying)]) {
            self[i] = [element mutableCopy];
        }
    }
}

@end

@implementation NSMutableDictionary (mutableLeavesAddition)

- (void)setLeavesMutable {
    for (NSString *key in [self allKeys]) {
        NSObject *element = self[key];
        if ([element isKindOfClass:NSMutableDictionary.class] || [element isKindOfClass:NSMutableArray.class]) {
            [(NSMutableDictionary*)element setLeavesMutable];
        } else if ([element.class conformsToProtocol:@protocol(NSMutableCopying)]) {
            self[key] = [element mutableCopy];
        }
    }
}

@end

注意:它仅在您在JSON解析期间选择NSJSONReadingMutableContainers时才有效。