[英]Adding new object to retrieved NSMutableArray - returns NSInternalInconsistencyException
[英]NSInternalInconsistencyException for NSMutableArray
我正在尝试将对象添加到NSMutableArray,但它一直给我这个错误。
NSInternalInconsistencyException', reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object
我已经研究了这个问题,并且没有做过以前人们做过的任何错误,所以我不知道哪里出了问题。 这是我的代码:
Group.h
@property (strong, nonatomic) NSString *custom_desc;
@property (strong, nonatomic) NSMutableArray *attributes; //I define the array as mutable
Group.m
#import "Group.h"
@implementation Group
-(id)init
{
self = [super init];
if(self)
{
//do your object initialization here
self.attributes = [NSMutableArray array]; //I initialize the array to be a NSMutableArray
}
return self;
}
@end
GroupBuilder.m
#import "GroupBuilder.h"
#import "Group.h"
@implementation GroupBuilder
+ (NSArray *)groupsFromJSON:(NSData *)objectNotation error:(NSError **)error
{
NSError *localError = nil;
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:objectNotation options:0 error:&localError];
if (localError != nil) {
*error = localError;
return nil;
}
NSMutableArray *groups = [[NSMutableArray alloc] init];
NSDictionary *results = [parsedObject objectForKey:@"result"];
NSArray *items = results[@"items" ];
for (NSDictionary *groupDic in items) {
Group *group = [[Group alloc] init];
for (NSString *key in groupDic) {
if ([group respondsToSelector:NSSelectorFromString(key)]) {
[group setValue:[groupDic valueForKey:key] forKey:key];
}
}
[groups addObject:group];
}
for(NSInteger i = 0; i < items.count; i++) {
//NSLog(@"%@", [[items objectAtIndex:i] objectForKey:@"attributes"]);
NSMutableArray *att = [[items objectAtIndex:i] objectForKey:@"attributes"]; //this returns a NSArray object understandable
Group *g = [groups objectAtIndex:i];
[g.attributes addObjectsFromArray:[att mutableCopy]]; //I use mutable copy here so that i'm adding objects from a NSMutableArray and not an NSArray
}
return groups;
}
@end
根据错误消息,您正在尝试将对象插入NSArray实例,而不是NSMutableArray实例。
我认为是在这里:
NSMutableArray *att = [[items objectAtIndex:i] objectForKey:@"attrib`enter code here`utes"]; //this returns a NSArray object understandable
Items
是从JSON提取的,因此是不可变的。 您可以通过创建可变对象的方式来配置JSONSerialization,但是我不知道到底该怎么做。 检查有关如何执行此操作或进行可变拷贝的参考:
NSMutableArray *att = [[items objectAtIndex:i] objectForKey:@"attributes"] mutableCopy];
下一次尝试,请考虑您对第一次尝试的答复:
#import "Group.h"
@implementation Group
-(NSMutableArray*)attributes
{
return [[super attributes] mutableCopy];
}
@end
使用options:NSJSONReadingMutableContainers
NSJSONSerialization调用上的NSJSONReadingMutableContainers。
然后,它创建的所有字典和数组都是可变的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.