Red Sun
Red Sun

Reputation: 147

NSPredicate filtering over array of complex objects

So, basically, the problem is, I have an object, let's call it "Product"

struct Product {
  let categories: [Category]
}

And Category looks like this:

struct Category {
  let id: Int
}

What I need, is to create NSPredicate, that would check if categories list contains Category of certain id. Now sure if it's possible, but maybe there's better workaround than creating another property with simple Int array? Update: NSPredicate is mandatory because I need to use it in Realm database filter query.

Upvotes: 2

Views: 644

Answers (3)

Pete Morris
Pete Morris

Reputation: 1562

The correct format for your NSPredicate would be:

let predicate = NSPredicate(format: "ANY categories.id == %@", argumentArray: [1])

The above example would return all Products whose categories array contains a Product with the id 1.

Of course, that's assuming that you're only looking for categories of a single id. If you needed to check for multiple ids, you could modify the above with an OR.

Note: I tested the above predicate with an NSArray, not Realm. However, if you check the Realm predicate cheatsheet, it does support all of the operators the predicate is using:

https://academy.realm.io/posts/nspredicate-cheatsheet/?_ga=2.32752254.1161432538.1537175891-1199086799.1527592477

Upvotes: 3

Bhavin Kansagara
Bhavin Kansagara

Reputation: 2916

You can simply check for the counts of the array returned by filter the categories.

struct Product {
  let categories: [Category]
}

struct Category {
  let id: Int
}

let c1 = Category(id: 1)
let c2 = Category(id: 2)
let c3 = Category(id: 3)

let p = Product(categories: [c1, c2, c3])
let yourCategoryId = 1
let filteredResults = p.categories.filter {
    $0.id == yourCategoryId
}
let isCategoryWithIdPresent = filteredResults.count > 0 ? true : false
print(isCategoryWithIdPresent)

Hope it helps

Upvotes: 0

Milander
Milander

Reputation: 1061

If you are using Swift you can use filter and contains method to filter arrays.

When you have an array with products you can filter it by:

let filteredProducts = products.filter{ $0.categories.contains(where: { $0.id == 1 })}

The code above filters the products that contains a category with id = 1

Upvotes: 0

Related Questions