I've contacts array where each contact is a dictionary.
Each contact has a key "contact_type" which is an NSNumber. Contact type basically represents whether its a Facebook, LinkedIn or Mail contact etc. I've a search array which holds only NSNumber of contact_type's.
What I want is to make a temporary array of contacts which I want to search using my search array.
I am facing trouble using NSPredicate to create searched contacts array. Can some one guide me on how to do it?
NSArray *contacts = ...; //your array of NSDictionary objects
NSPredicate *filter = [NSPredicate predicateWithFormat:@"contact_type = 42"];
NSArray *filteredContacts = [contacts filteredArrayUsingPredicate:filter];
After this, filteredContacts
will contain only the contacts whose contact_type
is 42
.
If you need to search for more than one kind of contact_type
, then simply use an OR
in the predicate:
filter = [NSPredicate predicateWithFormat:@"contact_type = 42 OR contact_type = 23"];
This solution work cool for me.
//NSDictionary Format
{
18=(
{
content="Great Avijit",
id=abc
}
),
13=(
{
content="Stack Overflow is cool",
id=abc
}
),
}
//Step 1
-(void)filterContentForSearchText:(NSString *)searchText
{
[self.filterResultArray removeAllObjects];
NSPredicate *namePredicate = [NSPredicate predicateWithFormat:@"(content contains[cd] %@)", searchText];//from_user.name
//other
for (NSMutableDictionary *key in self.messageAll) {
NSArray *array=[self.messageAll objectForKey:key];
array=[array filteredArrayUsingPredicate:namePredicate];
if ([array count]==0) {
[self.filterResultArray removeObject:key];
}
else{
if ([self.filterResultArray containsObject:key]) {
}
else{
[self.filterResultArray addObject:key];
}
}
}
//Reload table view
[self.tableView reloadData];
}
//Step 2: numberOfRowsInSection
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (self.searchController.active && ![self.searchController.searchBar.text isEqualToString:@""]) {
return [self.filterResultArray count];
}else{
return [keyArray count];//keyArray hold all key of original dict
}
}
//Step 3: In cellForRowAtIndexPath method
NSString *key = [self.filterResultArray objectAtIndex:indexPath.row];
NSDictionary *dictionary = [[self.messageAll objectForKey:key] lastObject];//self.messageAll is original dict
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With