-->

Searching through an array of dictionaries

2020-07-22 16:36发布

问题:

I'm making an iPhone app which displays information about red wines. The wines are stored in a plist containing an array of dictionaries. I'm adding a search view controller to the application, and to start up easy I want to get the wines who the value for the "Name" key contains nameString (from textbox).

It kind of stops here, I need some advices about the most suitable way of doing this. Is there a function in the NSArray class which will do the job, should bring in NSPredicate, NSUserDefaults, or are there other options? I've done some research but I'm going to need some advices and maybe an example to get started.

I will advance the search function to let the user include/exclude countries, get wines that suit this and that food, set minimum price, maximum price, and so on. The dictionaries have strings for all this info. So before I start on something advanced like this I'll need some advice for which functions could do my job the best.

-(IBAction)searchButtonPoke:(id)sender{

    NSString *path = [[NSBundle mainBundle] pathForResource:@"Wines" ofType:@"plist"];
    allObjectsArray = [[NSMutableArray alloc] initWithContentsOfFile:path];

    NSString *nameString = [NSString stringWithFormat:@"%@", [nameTextField text]];

    resultObjectsArray = /*objects where the value for the key "Name" contains
                                                                   nameString*/;

回答1:

How about simply iterating through the array and compare the names?

resultObjectsArray = [NSMutableArray array];
for(NSDictionary *wine in allObjectsArray)
{
   NSString *wineName = [wine objectForKey:@"Name"];
   NSRange range = [wineName rangeOfString:nameString options:NSCaseInsensitiveSearch];
   if(range.location != NSNotFound)
     [resultObjectsArray addObject:wine];
}

Swift version is even simpler:

let resultObjectsArray = allObjectsArray.filter{
    ($0["Name"] as! String).range(of: nameString,
                                  options: .caseInsensitive,
                                  range: nil,
                                  locale: nil) != nil
}

Cheers, anka



回答2:

This Works !!! tested !!!

for (NSDictionary* dict in Array) {

    if ([[dict objectForKey:@"key"] isEqualToString:string]) {

        Index = [Array indexOfObject:dict];
    }
}


回答3:

We can use NSPredicate too, like this:

NSPredicate *predicate =
  [NSPredicate predicateWithFormat:@"publisher == %@", @"Apress" ];
NSArray *filtered  = [bookshelf filteredArrayUsingPredicate:predicate];

If the publisher can be found in the bookshelf array, filtered count will be bigger than 0.

I thinks this way is much cleaner way to search. Hope it helps.



回答4:

remember to break; out your for loop once your object has been found