NSMutableArray和NSPredicate过滤 [英] NSMutableArray and NSPredicate filtering

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

问题描述

我试图过滤我的对象中的两个实体的数组,像我有一个Person对象,其中我有名称,地址,数字,电子邮件等等。我想过滤我的数组对象列表只是名称和数。使用NSPredicate如何实现?

I am trying to filter my array with two entities within an object like I have a Person object in which I have name, address, number, email, etc. I am trying to filter my array list of objects with just name and number. How can this be achieved with using NSPredicate?

推荐答案

创建谓词(以下假设您的 Person class name number 字符串属性):

Create the predicate (the following assumes that your Person class has name and number string properties):

NSString *nameFilter = @"Steve*";
NSString *numberFilter = @"555-*";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(name like %@) or (number like %@)", nameFilter, numberFilter];

然后,过滤数组(假设你有一个 NSArray of Person objects):

Then, filter the array (this assumes you have an NSArray of Person objects):

NSArray *personArray = /* obtain from somewhere */;
NSArray *filtered = [personArray filteredArrayUsingPredicate:pred];

结果将是包含 Person的数组 name 可能是Steve的对象,Steven其编号以 555 - 开头。

The result will be an array that contains Person objects whose name could be “Steve”, “Steven” etc, and whose number starts with 555-.

你说的话真的没有意义。您无法从类中移除属性(或者您不应)。如果你只想要一个只包含名称和数字的数组,你必须遍历 Person 对象数组:

What you're saying doesn't really make sense. You can't remove properties from a class (or rather, you shouldn't). If you just want an array that contains only the names and numbers you'll have to iterate through the array of Person objects:

NSMutableArray *result = [NSMutableArray array];

for (Person *p in personArray)
    [result addObject:[NSString stringWithFormat:"%@ : %@", [p name], [p number]]];

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

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