删除NSArray中具有条件的对象

时间:2014-03-26 16:55:01

标签: objective-c nsarray

例如,我有一个这样的数组,在每个对象中都有对象类型:

{
   {//ob1
   name = "zmg";
   link = "abccom";
   adress = "123 street";
   son = "2";
   },

   {//ob2
   name = "asf";
   link = "http://fsdfabccom";
   adress = "123 street";
   son = "1";
   },

   {//ob3
   name = "asf";
   adress = "123 street";
   son = "5";
   },

   {//ob4
   name = "sadfsdfasdf";
   link = "http://fsdfasdfasdfabc.com";
   adress = "123 street";
   son = "2";
   },

   {//ob5
   name = "asf";
   adress = "123 street";
   son = "4";
   },
}

如果我要删除所有没有对象“链接”的对象(在此示例中:ob3,ob5必须删除),我该怎么办? 结果必须是:

{
   {//ob1
   name = "zmg";
   link = "abccom";
   adress = "123 street";
   son = "2";
   },

   {//ob2
   name = "asf";
   link = "http://fsdfabccom";
   adress = "123 street";
   son = "1";
   },
   {//ob3
   name = "sadfsdfasdf";
   link = "http://fsdfasdfasdfabc.com";
   adress = "123 street";
   son = "2";
   },

}

非常感谢你!

4 个答案:

答案 0 :(得分:2)

这应该有效。您可以根据是否有链接来过滤给定的数组。

    NSArray *newArray = [array filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        return evaluatedObject.link;
    }];

在Swift中它更容易:

let filtered = array.filter { (item) -> Bool in
    return item > 2
}

答案 1 :(得分:1)

filteredArrayUsingPredicate(如上所述)是一个好主意,可以获取要删除的项目列表 - 然后创建一个新数组减去要删除的项目。

请注意,您也可以以相反的方式执行查询,以便返回要保留的项目数组。然后保留它并相应地使用它。

答案 2 :(得分:1)

试试这种方式。你应该阅读关于这个https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Predicates/Articles/pUsing.html

的苹果文档
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(link != null)"];
NSArray *array2 = [array filteredArrayUsingPredicate:predicate];

答案 3 :(得分:0)

这也应该有效:

NSArray* filteredArray = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"%@ IN self.@allKeys" ,@"link"]];