I have an NSArray
of custom objects that all have a @property name
of type NSString
. How can I quickly enumerate through the array and create a new array that contains only the objects that have a specific word in their name
property?
For instance:
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.
I know I could use a for loop like so:
NSMutableArray *newArray = [NSMutableArray array];
for (CustomObject *obj in testArray)
{
if ([obj.name rangeOfString:@"dog"].location == NSNotFound) {
//string wasn't found
}
else {
[newArray addObject:obj];
}
}
But is there a more efficient way? Thanks!