Swift CoreData using predicates with Array

I need to keep array of Strings in CoreData and later on use predicates for filtering data for that array.

According to this post field type Transformable (with custom class [String]) does the trick and I can properly save array of Strings: How to save Array to CoreData?

However, I can't use predicates for this fields. Specifically, my goal is to find all items where at least one item in saved array matches pattern.

So, back to question: is there a good way of storing array in CoreData so that I can apply predicates for it later on?

Upvotes: 2

Views: 1064

Answers (1)

Found an appropriate solution for CoreData

Don't put array as Transformable field in Entity

  1. Create separate Entity with a single field, use that entities instead of array.
  2. Create relation between main Entity and Array replacement Entity.
  3. During runtime: find CoreObject of array Entity using predicate:
NSPredicate(
    format: "%K = %@", #keyPath(YourArrayEntity.onlyField),
    matchingString
)
  1. Use predicates for searching your main entities
NSPredicate(
    format: "ANY %K == %@",
    #keyPath(YourMainEntity.relationToArrayEntity), 
    arrayEntityFoundInPreviousStep
)

Upvotes: 2

Related Questions