Ios 如何筛选NSArray
嘿,我想过滤一个NSArray。在这个数组中有很多信息,如姓名、城镇、电话号码等。但有些城镇在阵列中出现了两到三次。Ios 如何筛选NSArray,ios,objective-c,properties,filter,nsarray,Ios,Objective C,Properties,Filter,Nsarray,嘿,我想过滤一个NSArray。在这个数组中有很多信息,如姓名、城镇、电话号码等。但有些城镇在阵列中出现了两到三次。 我有一个城镇的房产。 因此,我只需要arry中与属性匹配的对象 例如: 阵列中有: 法兰克,纽约,123456 奥利弗,纽约,123456 托马斯,波士顿,123456 当物业位于纽约时,我想要olny对象1和2 有人知道我怎么做吗 这是我的代码: NSString *filterString = newsArticle; NSPredicate *prediacte = [NS
我有一个城镇的房产。
因此,我只需要arry中与属性匹配的对象 例如: 阵列中有:
NSString *filterString = newsArticle;
NSPredicate *prediacte = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"Ort == '%@'",filterString]];
newsTownArray = [news filteredArrayUsingPredicate:predicate];
当我说到这句话的时候:
cell.textLabel.text=[[newsTownArray objectAtIndex:indexPath.row] objectForKey:"Name"];
不过,您可以使用NSPredicate在一个数组中执行此操作,但我建议您做一些不同的操作,这将增加您的代码和良好的编程方式 创建一个自定义类
Person
,该类具有以下属性name
、city
和telephone
创建一个数组,用于存储Person
的对象
在此之后,您可以很容易地操作/过滤/排序等
你需要用这个
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"town == 'New York'"];
[yourArray filterUsingPredicate:predicate];
您可以动态创建谓词,如:
NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"town == '%@'",yourInput]];
这里的yourInput
是一个NSString
,它保存所需的城镇名称
请查看这些文章以了解更多详细信息:
使用此代码
NSMutableArray *subpredicates = [NSMutableArray array];
for(NSString *term in arryOfWordsToBeSearched) {
NSPredicate *p = [NSPredicate predicateWithFormat:@"self contains[cd] %@",term];
[subpredicates addObject:p];
}
NSPredicate *filter = [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];
result = (NSMutableArray*)[arryOfDummyData filteredArrayUsingPredicate: filter];
但这个城市并不总是一样的。那么这也是可能的吗?@theandrew:我将添加动态查询,仅此而已wait@theandrew:请现在查看:)非常感谢:)但我还必须使用从右一开始的第二行?@theandrew:是的,您需要使用该行,也可以使用可能的副本
NSMutableArray *subpredicates = [NSMutableArray array];
for(NSString *term in arryOfWordsToBeSearched) {
NSPredicate *p = [NSPredicate predicateWithFormat:@"self contains[cd] %@",term];
[subpredicates addObject:p];
}
NSPredicate *filter = [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];
result = (NSMutableArray*)[arryOfDummyData filteredArrayUsingPredicate: filter];