iphone - 搜索一系列字典

标签 iphone objective-c xcode search nsmutablearray

我正在制作一个显示有关红酒信息的 iPhone 应用程序。 Wine 存储在包含一系列字典的 plist 中。我正在向应用程序添加一个搜索 View Controller ,并且为了轻松启动,我想获取“名称”键的值包含 nameString(来自文本框)的 Wine 。

它有点停在这里,我需要一些关于最合适的方法的建议。 NSArray 类中是否有一个函数可以完成这项工作,应该引入 NSPredicate、NSUserDefaults,还是有其他选项?我已经做了一些研究,但我需要一些建议,也许还需要一个示例才能开始。

我将改进搜索功能,让用户包括/排除国家、找到适合这种和那种食物的 Wine 、设置最低价格、最高价格等。字典有所有这些信息的字符串。因此,在开始像这样的高级操作之前,我需要一些建议,了解哪些功能可以最好地完成我的工作。

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

最佳答案

简单地遍历数组并比较名称怎么样?

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

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

干杯, 安卡

关于iphone - 搜索一系列字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11731092/

相关文章:

cocoa - Cocoa 应用程序中的数组值 - 初始化程序不是常量错误

iphone - FMDatabase:执行操作:插入,更新,选择,删除

iphone - iOS 中如何使用套接字?

Objective-C - 以编程方式确定 iPod touch 的 IP 地址

ios - 按下物理音量键时如何触发iOS音量 View

xcode - 如何在 Swift 中的当前 View 顶部呈现模态

ios - SKSpriteNode 使用 UIColor 设置颜色

iphone - NSMutableString stringByReplacingOccurrencesOfString 警告

ios - 识别触摸移动方向

jquery - Joomla 1.5 如何隐藏我的网站源代码?