简体   繁体   中英

iOS - Using NSMutableDictionary for grouping

I have a method which is passed a dict (whose values themselves consist of nested dicts), and I am using recursion to traverse this dict, and I want to store only the information I need in another dict which is also passed to the method as the second argument.

So, the method (ignoring some optional arguments that's needed to aid recursion) looks like:

-(NSMutableDictionary*) extractData: (NSDictionary*)complicatedDict intoSimpleDict:(NSMutableDictionary*)simpleDict {
    // do recursive traversal of complicatedDict and return simpleDict
}

I am facing two problems:

a. I need to pass an empty dict initially when I first call the method. How do I initialize an empty NSMutableDictionary to pass as the simpleDict parameter?

b. I am trying to group values having common key in the simpleDict. In JS (which is my most familiar language), I will implement it like:

if( !simpleDict.hasOwnProperty('some_key') ) {
    simpleDict['some_key'] = [];
}
simpleDict['some_key'].push("value");

The above code would initially an array in each index of the dict, and push the value to it. How do I do this in objective-c?

a. Create an empty mutable dictionary simply like this

NSMutableDictionary *empty = [NSMutableDictionary dictionary];

b. This is equivalent to your JS example

if(![[simpleDict allKeys] containsObject:@"some_key"])
    [simpleDict setObject:[NSMutableArray array] forKey:@"some_key"];
[[simpleDict objectForKey:@"some_key"] addObject:@"value"];

a. You have a couple options here. For one, you could simply call your method like this:

[myObject extractData:complicatedDict intoSimpleDict:[NSMutableDictionary dictionary]];

That will create an autoreleased dictionary object that you can manipulate in your method body and return. Just remember that whoever needs to keep that dictionary should retain it.

The other way is to just create the dictionary in the method body:

-(NSMutableDictionary*) extractData:(NSDictionary*)complicatedDict {
    NSMutableDictionary *simpleDict = [NSMutableDictionary dictionary];
    // do recursive traversal of complicatedDict and return simpleDict
    return simpleDict;
}

b. Just saw @Joe posted and has a good solution for this.

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