0

NSMutableDictionary看起来像这样:

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

现在,当用户在我的应用程序中执行操作时,我会得到对象的 @"name"-value,例如“Apple”。我想从字典中删除该对象,但是如何使用

[myDictionary removeObjectForKey:]

方法?

4

2 回答 2

2

在高层次上,您需要获取对“描述”数组的引用。然后遍历数组获取每个字典。检查字典以查看它是否具有匹配的“名称”值。如果是这样,请从“描述”数组中删除该字典。

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;
    }
}
于 2013-04-14T22:08:00.323 回答
1

要从 INNER 数组中删除某些内容:

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

从外部数组中删除整个组(例如,“Fruits”)更简单。

于 2013-04-14T22:22:53.957 回答