简体   繁体   English

如何使用NSPredicate CONTAINS IN数组获取所有项目

[英]How to get all items with NSPredicate CONTAINS IN array

I have an array of objects and each has an id, and i want to get all items where item.objectID contains in an array of ids, how can i get that result ? 我有一个对象数组,每个都有一个id,我想得到item.objectID在一个id数组中包含的所有项目,我怎样才能得到那个结果?

What i tried to do but i have an error on creating predicateWithFormat: Unable to parse the format string : 我试图做但我在创建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];

I just what to avoid this: 我该怎么回避:

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

because there is other condition to add for filter. 因为还有其他条件要添加过滤器。

You almost had it :) 你几乎拥有它:)

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

And if you do not want to pass in any array, but write the predicate "in hand", the syntax would be: 如果您不想传入任何数组,但是“手持”编写谓词,则语法为:

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

And the result will be: 结果将是:

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

Only IN needed: 只有IN需要:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM