快速搜索NSArray中对象属性的方法

时间:2012-08-23 20:57:20

标签: objective-c algorithm

我有NSArray个自定义对象,它们都有name类型NSString。如何快速枚举数组并创建一个只包含name属性中具有特定单词的对象的新数组?

例如:

CustomObject *firstObject = [[CustomObject alloc] init];
firstObject.name = @"dog";

CustomObject *secondObject = [[CustomObject alloc] init];
secondObject.name = @"cat";

CustomObject *thirdObject = [[CustomObject alloc] init];
thirdObject.name = @"dogs are fun";

NSMutableArray *testArray = [NSMutableArray arrayWithObjects:firstObject,
                                                             secondObject,
                                                             thirdObject, 
                                                             nil];

// I want to create a new array that contains all objects that have the word 
// "dog" in their name property. 

我知道我可以像这样使用for循环:

NSMutableArray *newArray = [NSMutableArray array];
for (CustomObject *obj in testArray)
{
    if ([obj.name rangeOfString:@"dog"].location == NSNotFound) {
        //string wasn't found
    }

    else {
        [newArray addObject:obj];
    }
}

但是有更有效的方法吗?谢谢!

2 个答案:

答案 0 :(得分:5)

NSString *searchString = @"dog";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name contains %@", searchString];
NSArray *filteredArray = [testArray filteredArrayUsingPredicate:predicate];

答案 1 :(得分:1)

请查看NSPredicates!在搜索/过滤数组结果时,它们非常高效。这是 documentation!