2
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 改变不可变对象:”

有什么问题 ?

4

1 回答 1

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

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

于 2014-10-07T16:50:24.043 回答