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改变不可变对象:'
有什么问题?
答案 0 :(得分:0)
我刚遇到这个问题,确实很烦人。
我开发了一个解决方法,在NSMutableArray
和NSMutableDictionary
上添加了两个,它们解析整个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
时才有效。