PDA

View Full Version : Filtering an array with dictionary objects




Farani
Nov 8, 2008, 01:59 PM
I wasn't able to find much information on filtering an array of dictionary objects anywhere so I thought I'd post up some code to help people out.

Filtering is different than comparing. For instance, say you have "Tom Smith" in you array. When comparing, to get the right result you need to search starting with "Tom". For filtering, you could search "Smi" and get the result.

Most people will know this, but I thought I post up the details for newbies.

[filteredListContent removeAllObjects]; // clear the filtered array first

if([mySearchBar.text localizedCaseInsensitiveCompare:@""] != NSOrderedSame){
// Reallocate memory for the array to be filled with the new results
filteredListContent = [[NSMutableArray alloc] init];

// Loop through the full list array
for(int c = 0; c < [database count]; c++){
// Test if the element should be added to the list, we have done a simple case insensitive search for the sequence of characters anywhere in the string
NSRange range =[(NSString *)[[database objectAtIndex:c] objectForKey:@"name"] rangeOfString:mySearchBar.text options:NSCaseInsensitiveSearch];
if(range.location != NSNotFound){
[filteredListContent addObject:[database objectAtIndex:c]];
}
}
} else {
// Else is called when the UISearchBar is empty
filteredListContent = [[NSMutableArray alloc] initWithArray:database copyItems:YES];
}


database is the permanent database of dictionary objects, NSMutableArray.
filteredlistcontent is an NSMutableArray filled with the results of the search.
mySearchBar is a UISeachBar element.

I think everything is pretty self-explanatory.
I hope this helps someone!