Pregunta

In the header file:

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

in the .m file:

-(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"];
}

and I got

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

What did I do wrong? Can anyone point me to the right direction? Thanks in advance.

¿Fue útil?

Solución

Your array most likely contains only NSDictionary instances, not NSMutableDictionary instances, therefore you can't modify them. If you send NSJSONReadingMutableContainers to your JSONObjectWithDataCall you should get back mutable objects.

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

Otros consejos

The problem is that calling something an NSMutableDictionary (or array) doesn't make it one.

Basically this code is irrelevant:

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

What matters is what object you assigned to those properties.

This line...

vocab =  [vocabs objectAtIndex:vocabIndex];

Needs to be...

self.vocab = [NSMutableDictionary dictionaryWithDictionary:[vocabs objectAtIndex:vocabIndex]];
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top