marsrover
marsrover

Reputation: 715

NSDictionary: Find a specific object and remove it

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?

Upvotes: 0

Views: 2172

Answers (2)

Hot Licks
Hot Licks

Reputation: 47729

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.

Upvotes: 1

rmaddy
rmaddy

Reputation: 318794

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;
    }
}

Upvotes: 2

Related Questions