简体   繁体   中英

Core Data: Matching a combination of multiple items in a to-many relation

EDIT: Forgot to mention that I filter out cards with unwanted colors in Swift code afterwards.

So, this is yet another question regarding to-many relationships in Core Data and how to write a predicate for it. In short, I'd like to match a combination of multiple items in a to-many relation.

Setup

  1. Color table with five colors: Red, Green, White, Black, Blue
  2. Card table , each card has a to-many relation to color table

Goal

Search for cards with black and/or white color, meaning:

  1. Card may be black only
  2. Card may be white only
  3. Card may be both black and white

So far

Best results are (simplified):

NSPredicate(format: "ANY color == Black") // Only black cards, good
NSPredicate(format: "ANY color == White") // Only white cards, good
NSPredicate(format: "ANY color == Black OR ANY color == White") // Only black AND white cards, bad

There is a very similar post that concerns MySQL here, in case it helps further clarifying the issue:

SQL: Make colors from color-table searchable

根据@pbasdf的评论,我提出了以下解决方案(在实际代码中使用更好的语法):

// Desired colors let includePredicate = NSPredicate(format: “SUBQUERY(color, $C, $C == 'Black' OR $C == 'White').@count > 0”)

// Undesired colors let excludePredicate = NSPredicate(format: “SUBQUERY(color, $C, $C == 'Green' OR $C == 'Red' OR $C == 'Blue').@count == 0”)

// Combined to one predicate let finalPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [includePredicate, excludePredicate]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM