FROM : Chris Hanson
DATE : Mon Mar 03 05:45:19 2008
On Mar 2, 2008, at 12:31 PM, Tom Jones wrote:
> I have an NSArray which contains String values and I want to loop
> though it and determine if any of those string contain words I'm
> looking for. I have tried but have been unsuccessful.
Predicates are great for this. They're a Foundation facility for
performing queries on collections.
- (NSArray *)itemsInCollection:(NSArray *)collection containingWord:
(NSString *)word {
NSPredicate *containsWordPredicate = [NSPredicate @"SELF
CONTAINS[cd] %@", word];
return [collection
filteredArrayUsingPredicate:containsWordPredicate];
}
This will return a new collection containing all items in the passed-
in collection that themselvs contain the given word, and it will do
the comparison in a case-insensitive and diacritic-insensitive
fashion. (Thus if word is @"resume" then @"résumé" and @"Resume"
would be considered matches.)
In general, any time you can express something as a query rather than
as explicit iteration, it's a win -- whether you're talking about
Cocoa or any other framework. This is because it lets the framework
itself determine the best way to achieve the results, which can change
over time.
-- Chris
DATE : Mon Mar 03 05:45:19 2008
On Mar 2, 2008, at 12:31 PM, Tom Jones wrote:
> I have an NSArray which contains String values and I want to loop
> though it and determine if any of those string contain words I'm
> looking for. I have tried but have been unsuccessful.
Predicates are great for this. They're a Foundation facility for
performing queries on collections.
- (NSArray *)itemsInCollection:(NSArray *)collection containingWord:
(NSString *)word {
NSPredicate *containsWordPredicate = [NSPredicate @"SELF
CONTAINS[cd] %@", word];
return [collection
filteredArrayUsingPredicate:containsWordPredicate];
}
This will return a new collection containing all items in the passed-
in collection that themselvs contain the given word, and it will do
the comparison in a case-insensitive and diacritic-insensitive
fashion. (Thus if word is @"resume" then @"résumé" and @"Resume"
would be considered matches.)
In general, any time you can express something as a query rather than
as explicit iteration, it's a win -- whether you're talking about
Cocoa or any other framework. This is because it lets the framework
itself determine the best way to achieve the results, which can change
over time.
-- Chris
| Related mails | Author | Date |
|---|---|---|
| Tom Jones | Mar 2, 21:31 | |
| Seth Willits | Mar 2, 22:39 | |
| Andrew Merenbach | Mar 2, 22:44 | |
| j o a r | Mar 2, 23:01 | |
| Johannes Huning | Mar 2, 23:02 | |
| Andrew Merenbach | Mar 2, 23:16 | |
| Chris Hanson | Mar 3, 05:45 | |
| Jens Alfke | Mar 3, 07:50 |






Cocoa mail archive

