我有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];
}
}
但是有更有效的方法吗?谢谢!
答案 0 :(得分:5)
NSString *searchString = @"dog";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name contains %@", searchString];
NSArray *filteredArray = [testArray filteredArrayUsingPredicate:predicate];
答案 1 :(得分:1)
请查看NSPredicates
!在搜索/过滤数组结果时,它们非常高效。这是 documentation!