问题
I have NSMutableDictionary
that looks like this:
category = (
{
description = (
{
id = 1;
name = Apple;
},
{
id = 5;
name = Pear;
},
{
id = 12;
name = Orange;
}
);
id = 2;
name = Fruits;
},
{
description = (
{
id = 4;
name = Milk;
},
{
id = 7;
name = Tea;
}
);
id = 5;
name = Drinks;
}
);
Now, when a user performs an action in my application, I get the @"name"-value of the object, like "Apple". I would like to remove that object from the dictionary, but how will can I reach this object with the
[myDictionary removeObjectForKey:]
method?
回答1:
At a high level you need to get a reference to the "description" array. Then iterate through the array getting each dictionary. Check the dictionary to see if it has the matching "name" value. If so, remove that dictionary from the "description" array.
NSString *name = ... // the name to find and remove
NSMutableArray *description = ... // the description array to search
for (NSUInteger i = 0; i < description.count; i++) {
NSDictionary *data = description[i];
if ([data[@"name"] isEqualToString:name]) {
[description removeObjectAtIndex:i];
break;
}
}
回答2:
To remove something from an INNER array:
NSString* someFood = <search argument>;
NSArray* categories = [myDictionary objectForKey:@"category"];
for (NSDictionary* category in categories) {
NSArray* descriptions = [category objectForKey:@"description"];
for (int i = descriptions.count-1; i >= 0; i--) {
NSDictionary* description = [descriptions objectForIndex:i];
if ([[description objectForKey:@"name"] isEqualToString:someFood]) {
[descriptions removeObjectAtIndex:i];
}
}
}
To remove an entire group (eg, "Fruits") from the outer array is simpler.
来源:https://stackoverflow.com/questions/16004770/nsdictionary-find-a-specific-object-and-remove-it