从NSMutableArray中删除一个值

时间:2014-04-24 08:19:03

标签: ios objective-c nsmutablearray nspredicate

我有NSMutableArray名为_groupCategoryCurrentIds,其数据采用此格式

(
        {
        id = 2;
        name = Fashion;
    },
        {
        id = 5;
        name = Leisure;
    },
        {
        id = 14;
        name = Clothing;
    },
        {
        id = 17;
        name = Sports;
    },
        {
        id = 2;
        name = Fashion;
    },
        {
        id = 36;
        name = Men;
    },
        {
        id = 34;
        name = Woodland;
    },
        {
        id = 30;
        name = Accessories;
    },
        {
        id = 4;
        name = Entertainment;
    },
        {
        id = 40;
        name = Education;
    }
)

我试图删除id = 40的对象,这就是我的工作方式

_groupCategoryCurrentIds = [[_groupCategoryCurrentIds filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"NOT id IN %@", @"40"]] mutableCopy];

但是这也会删除id = 4的对象。我有什么建议吗?

1 个答案:

答案 0 :(得分:5)

使用

[NSPredicate predicateWithFormat:@"id != %@", @"40"]

[NSPredicate predicateWithFormat:@"id != %@", @40]

取决于id是以字符串还是以数字形式存储。

请注意,您可以将代码简化为

[_groupCategoryCurrentIds filterUsingPredicate:...];

如果_groupCategoryCurrentIds是一个可变数组。


谓词中的“IN”用于测试数组或集合中的成员资格,例如

[NSPredicate predicateWithFormat:@"NOT id IN %@", @[@40, @50]]

获取id既不是40也不是50的所有对象。

未记录在右侧使用“IN”和字符串Predicate Programming Guide。 它似乎表现得像“是一个子串”,所以在你的情况下

[NSPredicate predicateWithFormat:@"NOT id IN %@", @"40"]

给出id不是“40”子字符串的所有对象。这可以解释你的结果。 但同样,这不是记录在案的行为。

相关问题