如何使用setValue或setObject修改NSMutableDictionary?

时间:2014-03-26 17:20:00

标签: ios objective-c nsmutabledictionary

在头文件中:

@property (strong, nonatomic) NSMutableArray *vocabs;
@property (strong, nonatomic) NSMutableDictionary *vocab;
<。>文件中的

-(void) loadFile {
    NSString* filepath = [[NSBundle mainBundle]pathForResource:@"vocabs" ofType:@"json"];

    NSData *data = [NSData dataWithContentsOfFile:filepath];

    vocabs = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];



}

-(void) renderVocabs {
    //NSLog(@"json file = %@", vocabs);
    if ([vocabs count] == 0) {

    } else {

        vocab =  [vocabs objectAtIndex:vocabIndex];
        //NSLog(@"%d", vocabIndex);
        //NSLog(@"%d", [vocabs count]);
        NSString *word = [vocab objectForKey:@"word"];

        labelWord.text = word;

        tvDefinitions.text = [NSString stringWithFormat:@"(%@) %@" , [vocab objectForKey:@"subject"], [vocab objectForKey:@"definitions"]];

        NSString *imgName = [NSString stringWithFormat:@"%@.jpg",word];
        NSLog(@"%@", imgName);
        [imageVocab setImage: [UIImage imageNamed:imgName]];

        NSString *remembered = [vocab objectForKey:@"remembered"];

        if ([remembered isEqualToString:@"0"]) {

            self.btnRemember.hidden = FALSE;

        } else {

            self.btnRemember.hidden = TRUE;

        }

    [self setDisplayFontSize];

    }
}
- (IBAction)btnTick:(UIButton *)sender {
    [vocab setObject:@"1" forKey:@"remembered"];
}

我得到了

** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'
*** First throw call stack:

我做错了什么?有人能指出我正确的方向吗?提前谢谢。

3 个答案:

答案 0 :(得分:2)

问题是调用某个NSMutableDictionary(或数组)没有使一个。

基本上这段代码无关紧要:

@property (strong, nonatomic) NSMutableArray *vocabs;
@property (strong, nonatomic) NSMutableDictionary *vocab;

重要的是您为这些属性分配的对象

答案 1 :(得分:2)

您的数组很可能仅包含NSDictionary个实例,而不包含NSMutableDictionary个实例,因此您无法修改它们。如果您将NSJSONReadingMutableContainers发送到JSONObjectWithDataCall,则应该收回可变对象。

self.vocabs = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error:nil];

答案 2 :(得分:1)

这一行...

vocab =  [vocabs objectAtIndex:vocabIndex];

需要...

self.vocab = [NSMutableDictionary dictionaryWithDictionary:[vocabs objectAtIndex:vocabIndex]];