我刚遇到这个问题,确实很烦人。
我已经开发了一个解决方法,其中添加了两个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
注意:它仅在您NSJSONReadingMutableContainers
在 JSON 解析期间选择时才有效。