NSDictionary: Find a specific object and remove it

混江龙づ霸主 提交于 2020-01-07 05:27:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!