【问题标题】:How to filter NSFetchedResultsController with relationship - Swift 3如何使用关系过滤 NSFetchedResultsController - Swift 3
【发布时间】:2017-07-27 03:06:38
【问题描述】:

我正在使用NSFetchedResultsController 在表格视图中显示数据。我有 2 个对象,客户端和公式。一个Client 可以有多个Formulas,但一个公式只能有一个Client,因此是一对多的关系。当我在table view cell 中点击某个Client 时,我只想看到与该客户端相关的公式,但是当我点击其他单元格时,这些单元格包含相同的公式对象,因此它没有过滤。我知道我需要使用谓词来过滤fetch request,但我不知道从哪里开始。

这是我设置的fetchedResultsController

let fetchedResultsController: NSFetchedResultsController<Formula> = {
    let fetchRequest: NSFetchRequest<Formula> = Formula.fetchRequest()
    let sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
    fetchRequest.sortDescriptors = sortDescriptors

    return NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: CoreDataStack.context, sectionNameKeyPath: "date", cacheName: nil)
}()

所以在某处,我必须添加fetchRequest.predicate = NSPredicate(format: ...),但我不知道在该初始化程序中输入什么。

【问题讨论】:

  • format: "theAttributeOfFormulaThatLinksItToAClient.anAttributedOfClientThatCanIdentifiyIt == %@", theClientSelectedIDValueThatCanIdentifyIt。我们需要看看你的模型,但这或多或少是要做的。
  • 我的模型是一个 .datamodeld 文件
  • @Larme 这就是我尝试过的:let predicate = NSPredicate(format: "client.formulas == %@", CVARARG)。我不知道该为 CVarArg 放什么。

标签: swift swift3 nspredicate nsfetchedresultscontroller


【解决方案1】:

正如您在问题中提到的,您需要在获取请求中添加谓词以过滤获取的对象。在该谓词中,您需要使用从FormulaClient 的反向关系。像这样:

fetchRequest.predicate = NSPredicate(format: "parentClient == %@", parentClient)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多