NSMutableArray的NSInternalInconsistencyException

时间:2014-05-18 11:25:30

标签: ios objective-c 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

3 个答案:

答案 0 :(得分:0)

根据错误消息,您尝试将对象插入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]; 

答案 1 :(得分:0)

接下来尝试一下,考虑一下您对第一次尝试的回复:

#import "Group.h"

@implementation Group
-(NSMutableArray*)attributes
{
    return [[super attributes] mutableCopy];
}
@end

答案 2 :(得分:0)

在NSJSONSerialization调用上使用options:NSJSONReadingMutableContainers

然后它创建的所有字典和数组都是可变的。