我有一个NSArray
自定义对象,它们都有一个 @propertyname
类型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];
}
}
但是有没有更有效的方法?谢谢!