简体   繁体   中英

Replacing key-values in NSDictionary

I have an NSDictionary like this :

{
"name": "Hayagreeva", //String
"age": 3,  //Number
"subjects": {  //Array
    "rhymes": {   //Dictionary 1
        "test1": 10,
        "test2": 20,
        "test3": 30
    },
    "games": {  //Dictionary 2
        "test1": 40,
        "test2": 50,
        "test3": 60
    },
    "crayoning": { //Dictionary 3
        "test1": 70,
        "test2": 80,
        "test3": 90
    }
},
"date": "2008-02-16T10:06:00Z"  //Date
}

Now I need to replace the value for key subjects > games > test1 from 40 to value 60. I know the lenghty process of taking another dictionary objects and create a similar dictionary but that process is time consuming and may be a wrong strategy. I have searched many questions also here but all of them have the way to remove the key for the first level dictionary (like removing key "subjects" in the above code). So I want to know if there is an easy and efficient way to update the value for key in an inner level as I need to execute this process at many situations in my current project. Thanks in advance.

Edit : I also tried something like

[dict removeValueForKey:@"subjects.games.test1"];

But that doesn't work. I hope that this line helps you to understand the desired functionality by me.

If that structure is set in stone and will not change then it's as simple as:

NSDictionary *topLevelDict = ...;
topLevelDict[@"subjects"][@"games"] = @{
    @"test1" : @(60),
    @"test2" : @(50),
    @"test3" : @(60)
};

Dictionaries of dictionaries are a pain to manipulate and it's always better to create a custom model object that allows easier manipulation, validation with the additional benefit of domain-specific functionality like serialization etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM