【问题标题】:NSPredicate filter arrayNSPredicate 过滤器数组
【发布时间】:2011-12-21 16:02:13
【问题描述】:

如何使用 NSPredicate 过滤数组的 ->_title 变量中的对象等于变量 title 的数组?我在下面尝试了以下方法,但它没有过滤掉任何东西。

NSMutableArray *array = [[posts mutableCopy] autorelease];
NSString *title = [[TBForrstr sharedForrstr] stringForPostType:type];
[array filterUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"SELF->_title == %@", title]]];

【问题讨论】:

    标签: objective-c nsarray nspredicate


    【解决方案1】:

    确保标题在数组中完全匹配。或者,如果您想更灵活,请使其不区分大小写:

    NSMutableArray *array = [[posts mutableCopy] autorelease];
    NSString *title = [[TBForrstr sharedForrstr] stringForPostType:type];
    [array filterUsingPredicate:[NSPredicate predicateWithFormat:@"_title == [cd]%@", title]];
    

    【讨论】:

    • stringWithFormat: 不是必须的,直接使用predicateWithFormat: 即可!
    • 我的错。复制/粘贴:D。固定。
    【解决方案2】:

    这个对我有用 - 注意字符串周围的单引号:

    NSArray *posts = [NSArray arrayWithObjects:
        [NSDictionary dictionaryWithObjectsAndKeys: @"Cat or dog?", @"_title", nil],
        [NSDictionary dictionaryWithObjectsAndKeys: @"I saved a file, where is it?", @"_title", nil],
        [NSDictionary dictionaryWithObjectsAndKeys: @"How should I do this?", @"_title", nil],
    nil];
    
    NSMutableArray *array = [[posts mutableCopy] autorelease];
    NSString *title = @"Cat or dog?";
    [array filterUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"SELF._title == '%@'", title]]];
    
    NSLog(@"%@", array);
    

    【讨论】:

      【解决方案3】:

      只需使用类似的东西:

      [NSPRedicate predicateWithFormat:@"title LIKE %@",title]
      

      标题应通过 KVC 与您的 _title ivar 匹配

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多