【问题标题】:Swift CoreData using predicates with ArraySwift CoreData 使用带有 Array 的谓词
【发布时间】:2019-03-11 16:56:46
【问题描述】:

我需要在 CoreData 中保留字符串数组,然后使用谓词过滤该数组的数据。

根据这个帖子字段类型可转换(使用自定义类 [String])可以解决问题,我可以正确保存字符串数组: How to save Array to CoreData?

但是,我不能对这个字段使用谓词。具体来说,我的目标是找到已保存数组中至少一项与模式匹配的所有项。

那么,回到问题:有没有一种在 CoreData 中存储数组的好方法,以便我以后可以为它应用谓词?

【问题讨论】:

  • 是的,该帖子以某种方式回答了。但是我不能使用它,因为不熟悉 Objective-C
  • 另一种可能的解决方案 - 使用可能的数组值创建另一个实体并在我的对象和新实体之间创建关系。
  • 是的。如果可以,请避免使用可变形的属性。

标签: swift core-data nspredicate


【解决方案1】:

CoreData找到了合适的解决方案

不要将数组作为Transformable字段放在Entity

  1. 使用单个字段创建单独的 Entity,使用该实体而不是 array
  2. 在主 Entity 和数组替换 Entity 之间创建关系。
  3. 运行时:使用谓词查找数组EntityCoreObject
NSPredicate(
    format: "%K = %@", #keyPath(YourArrayEntity.onlyField),
    matchingString
)
  1. 使用谓词搜索主要实体
NSPredicate(
    format: "ANY %K == %@",
    #keyPath(YourMainEntity.relationToArrayEntity), 
    arrayEntityFoundInPreviousStep
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多