搜索一系列词典 [英] Searching through an array of dictionaries

查看:180
本文介绍了搜索一系列词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一款显示红葡萄酒信息的iPhone应用程序。这些葡萄酒储存在含有一系列字典的plist中。我正在向应用程序添加一个搜索视图控制器,并且为了轻松启动我想要获得名称键的值包含 nameString(来自文本框)的葡萄酒。

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).

这种情况在此停止,我需要一些关于最合适的方法的建议。在NSArray类中是否有一个函数可以执行此任务,应该引入NSPredicate,NSUserDefaults,还是有其他选项?我做了一些研究,但我需要一些建议,也许还有一个例子可以开始。

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*/;


推荐答案

如何简单地遍历数组并比较名称?

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版本更简单:

Swift version is even simpler:

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

干杯,
anka

Cheers, anka

这篇关于搜索一系列词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆