Martin Herman
Martin Herman

Reputation: 888

Removing all values (strings) matching a search term from arrays located in a dictionary?

Currently I'm programming an app with a tableView, similar to that one in the iPhone Contacts app.

Everything works (the sections, the bar on the right showing the titles, the cells are configured...), beside the search bar. I'm familiar how to do this (search) if the tableView's data is loaded from an array, but my situation is that its loaded from arrays located in a NSDictionary.

The dict looks like

Key = "A" >> Value = "array = apple, animal, alphabet, abc ..."
Key = "B" >> Value = "array = bat, ball, banana ..."

How can I remove all strings (from all of the dictionary's arrays) matching the search term?

Thanks a lot in advance :)

Upvotes: 0

Views: 588

Answers (3)

Akshay
Akshay

Reputation: 5765

From you comments, I understand that you want to filter the table contents on the basis of what the user enters in the text field. For this, you do not need to modify your dictionary at every character change. The UISearchDisplayController is provided for exactly this scenario. Have a look at the reference for details: http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UISearchDisplayController_Class/Reference/Reference.html.

HTH,

Akshay

Upvotes: 1

Mihai Fratu
Mihai Fratu

Reputation: 7663

Well you can do it like this

NSMutableDictionary *newItems = [NSMutableDictionary dictionary];
for (NSString *key in oldItems) {
    NSMutableArray *newArray = [NSMutableArray array];
    for (NSString *item in [oldItems objectForKey:key]) {
        if ([item rangeOfString:searchTerm].location != NSNotFound) {
            [newArray addObject:item];
        }
    }
    if ([newArray count]) {
        [newItems setObject:newArray forKey:key];
    }
}
[oldItems release];
oldItems = [newItems retain];

I don't know if this is the best way to do it or even if it's faster enough but let me know if this works for you.

Upvotes: 2

Craig Stanford
Craig Stanford

Reputation: 1803

Did you want to update the existing Dictionary with the new Array that excludes that string?

NSMutableDictionary* excludedDictionary = [NSMutableDictionary dictionaryWithDictionary:existingDictionary];

for(id key in [existingDictionary allKeys])
{
   NSArray* existingArray = [existingDictionary objectForKey:key];
   NSPredicate* predicate = [NSPredicate predicateWithFormat:@"self != %@", excludedString];
   NSArray* excludedArray = [existingArray filteredArrayUsingPredicate:predicate];
   [excludedDictionary setObject:excludedArray forKey:key];
}
existingDictionary = [NSDictionary dictionaryWithDictionary:excludedDictionary];

This will replace your existing dictionary with one that doesn't have the string in it...

Upvotes: 1

Related Questions