user1951992
user1951992

Reputation:

Key value coding failure

So I have some json in a file like so

{
"address": {
    "home": {
        "street": "A Street"
    }
}

}

I pull out the json string like so

NSString *string = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];

I want to change a value on the fly, using a key path, so I need to make a deep mutable copy of the structure. So I am doing it like so

id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
data = [NSKeyedArchiver archivedDataWithRootObject:json];
json = [NSKeyedUnarchiver unarchiveObjectWithData:data];

Using breakpoints I can see the json and it all looks fine. However, I get a crash on this line

[json setValue:@"Different Street" forKeyPath:@"address.home.street"];

The compiler suggested there isn't a key at this key path that conforms to key-value coding.

Annoyingly, this line works fine and returns the street string

id value = [json valueForKeyPath:@"address.home.street"];

Why can't I set a value like this?


Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSDictionaryI 0x1741bb580> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key pan.'

Upvotes: 1

Views: 138

Answers (1)

Sam Corder
Sam Corder

Reputation: 5422

Use NSJSONReadingMutableContainers when reading your JSON. By default your containers are read in as immutable containers.

id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments|NSJSONReadingMutableContainers error:nil];

Upvotes: 2

Related Questions