How to get all items with NSPredicate CONTAINS IN array

我是研究僧i 提交于 2019-12-10 13:28:26

问题


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 ?

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.


回答1:


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



回答2:


Only IN needed:

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


来源:https://stackoverflow.com/questions/30237717/how-to-get-all-items-with-nspredicate-contains-in-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!