Search code examples
iosswiftrealmnspredicate

NSPredicate format for check the 2 array and filter those array


I have one array called A , and i have one realm result list called B. Now i have to filter my B based on the values contains in A. So that, my B will have only values object which contains A.

Here is my code :

var peopleObjectId: [String] = ["1", "2", "4", "6"]
var list  = Results<userData>

my list contains all the object about the user. Now by using below filter. I have to filer my list value which my peopleObjectId contains

list = list.filter(NSPredicate(format: "peopleID CONTAINS %@", peopleObjectId))

I know i should not use peopleObjectId directly. Not sure how can i achieve this.

Any help would be useful.

Thanks in advance


Solution

  • You can use the IN keyword:

    IN

    Left hand expression must appear in collection specified by right hand expression. i.e. name IN {‘Milk’, ‘Eggs’, ‘Bread’}

    Ref: NSPredicate Cheatsheet

    let found = list.filter { (user) in
        NSPredicate(format: "SELF IN %@", peopleObjectId)
            .evaluate(with:user.peopleID)
    }
    

    More Reading on NSPredicate: