Searching through an array of dictionaries

戏子无情 提交于 2019-12-04 12:55:24

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

Mangesh

This Works !!! tested !!!

for (NSDictionary* dict in Array) {

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

        Index = [Array indexOfObject:dict];
    }
}

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!