通过NSString过滤字典数组 [英] Filter array of dictionaries by NSString

查看:132
本文介绍了通过NSString过滤字典数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在实现搜索功能时,我需要过滤字典数组。我正在使用自动完整的文本字段方法搜索栏并将其存储到字符串中。我能够解析数组,但面对json下面

while implementing search functionality I need to filter array of dictionaries. I am using auto complete textfield method for search bar and am storing it into string. I can able to parse the array,But facing with below json

[{"CertProfID":"4","Name":"Dodge","Location":"loc4","City":"city4","State":"state4","Zip":"zip5","Website":"http:\/\/cnn.com","Phone":"phone4","Email":"email4"},
{"CertProfID":"5","Name":"cat","Location":"loc5","City":"city5","State":"State5","Zip":"zip5","Website":"web5","Phone":"phone5","Email":"email5"}]

这里我需要过滤字典以使其完成

Here I need to filter the dictionaries to make it finish

我尝试使用下面的代码,但是它的返回数组为空值:(

I tried with below code but its returning array with null values :(

 NSString *substring = [NSString stringWithString:textField.text];
  NSLog(@"substring %@",substring);
  NSMutableArray *arr2Filt= [arraylist valueForKey:@"Name"];
  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF  contains[c] %@",substring];
  filteredarr = [NSMutableArray arrayWithArray:[arr2Filt filteredArrayUsingPredicate:predicate]];


推荐答案

此代码将解决您的问题,它将返回一个字典数组

This code will solve your problem it will return an array of dictionaries

NSString *substring = [NSString stringWithString:textField.text];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Name contains[c] %@",searchString];
NSArray *filteredArry=[[arrayOfDict filteredArrayUsingPredicate:predicate] copy];




arrayOfDict是你原来的词典数组

arrayOfDict is your original array of dictionaries

Swift 3.0版本 :::

var namePredicate = NSPredicate(format: "Name contains[c] %@",searchString);

let filteredArray = arrayOfDict.filter { namePredicate.evaluate(with: $0) };

print("names = ,\(filteredArray)")

希望它会帮助你

这篇关于通过NSString过滤字典数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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