【问题标题】:How to get all items with NSPredicate CONTAINS IN array如何使用 NSPredicate CONTAINS IN 数组获取所有项目
【发布时间】:2015-05-14 12:43:56
【问题描述】:

我有一个对象数组,每个对象都有一个 id,我想获取 item.objectID 包含在一个 id 数组中的所有项目,我怎样才能得到这个结果?

我尝试做什么,但在创建 predicateWithFormat 时出错:无法解析格式字符串

NSString *predicateFormat = [NSString stringWithFormat:@"SELF.itemID CONTAIN IN (1,2,3,4,5,6,7,8)"];
NSPredicate *predicate = [NSPredicate predicateWithFormat: predicateFormat];
filteredData = [localData filteredArrayUsingPredicate:predicate];

我只是为了避免这种情况:

NSString *predicateFormat = [NSString stringWithFormat:@"SELF.itemID = 1 OR SELF.itemID = 2 OR SELF.itemID = 3"];
NSPredicate *predicate = [NSPredicate predicateWithFormat: predicateFormat];
filteredData = [localData filteredArrayUsingPredicate:predicate];

因为过滤器还有其他条件要添加。

【问题讨论】:

  • 上面用 CONTAINS IN 编写的代码是完美的。你想达到什么,请详细说明。
  • 我更新了我的问题。

标签: ios arrays nspredicate


【解决方案1】:

你几乎拥有它:)

    NSArray *objects = @[
        @{
            @"itemID" : @1
        },
        @{
            @"itemID" : @2
        },
        @{
            @"itemID" : @3
        },
        @{
            @"itemID" : @4
        },
        @{
            @"itemID" : @5
        }
    ];

    NSArray *idsToLookFor = @[@3, @4];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"itemID IN %@", idsToLookFor];
    NSArray *result = [objects filteredArrayUsingPredicate:predicate];

    NSLog(@"result: %@", result);

如果你不想传入任何数组,而是写谓词“in hand”,语法是:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"itemID IN { 3, 4 }"];

结果将是:

result: (
        {
        itemID = 3;
    },
        {
        itemID = 4;
    }
)

【讨论】:

  • 没有传递任何数组的第二个答案是有效的,谢谢你救了我!
【解决方案2】:

只需要IN

NSArray * desiredIDs = @[@1, @2, @3, @4, @5];
NSString * predicateFormat = [NSString stringWithFormat:@"SELF.itemID IN %@", desiredIDs];
...

【讨论】:

  • 我也试过了,我只是复制/粘贴你的答案,我得到了同样的错误:无法解析格式字符串“SELF.itemID IN (1, 2,3,4, 5)
  • @ConstantinSaulenco 我更新了我的答案以包含一个变体而不将任何数组传递给谓词。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-27
相关资源
最近更新 更多