1

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!

4

2 に答える 2

5
NSString *searchString = @"dog";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name contains %@", searchString];
NSArray *filteredArray = [testArray filteredArrayUsingPredicate:predicate];
于 2012-08-23T21:01:56.107 に答える
1

ぜひご覧くださいNSPredicates!配列結果を検索/フィルタリングする場合、これらは非常に効率的です。これがドキュメントです!

于 2012-08-23T20:59:59.193 に答える