如何使用NSPredicate CONTAINS IN数组获取所有项目 [英] How to get all items with NSPredicate CONTAINS IN array

查看:84
本文介绍了如何使用NSPredicate CONTAINS IN数组获取所有项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,每个对象都有一个id,我想获取item.objectID包含在id数组中的所有项目,我如何得到该结果?

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 ?

我尝试执行的操作,但是在创建predicateWithFormat时出错:无法解析格式字符串

What i tried to do but i have an error on creating predicateWithFormat: Unable to parse the format string:

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.

推荐答案

您几乎拥有了:)

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

结果将是:

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

这篇关于如何使用NSPredicate CONTAINS IN数组获取所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆