【问题标题】:How to filter a NSArray如何过滤 NSArray
【发布时间】:2013-01-04 12:47:55
【问题描述】:

嘿,我想过滤一个 NSArray。在这个数组中有很多信息,如姓名、城镇、电话号码等。但有些城镇是数组的两倍或三倍。
我有房产,里面有一个小镇。
所以我只想要数组中与属性匹配的那些对象。

例如: 在阵列中的立场:

  1. 弗兰克,纽约,123456
  2. 奥利弗,纽约,123456
  3. 托马斯,波士顿,123456

当房产是纽约时,我想要 olny 对象 1 和 2。

有人知道我该怎么做吗?

这是我的代码:

NSString *filterString = newsArticle;
NSPredicate *prediacte = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"Ort == '%@'",filterString]];
newsTownArray = [news filteredArrayUsingPredicate:predicate];

当我来排队时:

cell.textLabel.text=[[newsTownArray objectAtIndex:indexPath.row] objectForKey:"Name"];

【问题讨论】:

标签: ios objective-c properties filter nsarray


【解决方案1】:

但是,您可以使用 NSPredicate 在数组中执行此操作,但我建议您做一些不同的事情,这将增加您的代码和良好的编程方式。

创建一个自定义类Person 具有这些属性namecitytelephone

创建一个数组来存储Person 的对象。

在此之后,您可以很容易地操作/过滤/排序等。


NSString *filterCity=@"Delhi";

NSMutableArray *yourArray=[NSMutableArray arrayWithArray:self.persons];
NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"city == '%@'",filterCity]];
[yourArray filterUsingPredicate:predicate];

NSLog(@"Filtered");
for (Person *per in yourArray) {
    NSLog(@"Name: %@, City: %@, Telephone: %@",per.name, per.city, per.telephone);

}

【讨论】:

    【解决方案2】:

    您需要为此使用NSPredicate

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"town == 'New York'"];
    [yourArray filterUsingPredicate:predicate];
    

    您可以动态创建谓词,例如:

    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"town == '%@'",yourInput]];
    

    这里的yourInput 是一个NSString,其中包含所需的城镇名称。

    请查看这些文章了解更多详情:

    1. codeproject
    2. useyourloaf

    【讨论】:

    • 但小镇并不总是一样。那么这也可能吗?
    • @theandrew:我会添加动态查询,请稍等
    • @theandrew:请立即查看 :)
    • 非常感谢 :) 但我也必须使用第一行的第二行吗?
    • @theandrew:是的,您还需要使用该行
    【解决方案3】:

    使用此代码

    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];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-26
      • 1970-01-01
      • 1970-01-01
      • 2012-06-23
      • 1970-01-01
      相关资源
      最近更新 更多