【问题标题】:How do you pass a predicate through a relationship in CoreData如何通过 CoreData 中的关系传递谓词
【发布时间】:2018-01-08 17:14:42
【问题描述】:

我正在尝试让拥有timeOnIce 并设置了我的谓词的玩家。我希望它只会返回timeOnIce中的值的玩家

lazy var fetchedResultsControllerAllPlayersWithShifts: NSFetchedResultsController<Players> = {

    let fetchRequest: NSFetchRequest<Players> = Players.fetchRequest()
    let sort = NSSortDescriptor(key: #keyPath(Players.lastName), ascending: true)
    fetchRequest.sortDescriptors = [sort]

    let predicate               = NSPredicate(format: "%K > 0", #keyPath(Players.playersShiftRelationship.timeOnIce))
    fetchRequest.predicate      = predicate

    fetchRequest.propertiesToFetch = [#keyPath(Shifts.playersRelationship)]

    let fetchedResultsControllerAllPlayersWithShifts = NSFetchedResultsController( fetchRequest: fetchRequest, managedObjectContext: managedContext, sectionNameKeyPath: nil, cacheName: nil)

    fetchedResultsControllerAllPlayersWithShifts.delegate = self

    return fetchedResultsControllerAllPlayersWithShifts
}()

错误:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid keypath playersRelationship passed to setPropertiesToFetch:'

【问题讨论】:

    标签: swift core-data nsfetchedresultscontroller


    【解决方案1】:

    您正在获取 Players,但设置属性以从 Shifts

    获取

    编辑:

    fetchRequest.propertiesToFetch 只是设置要预加载的字段列表。如果未指定,则 fetchRequest 将返回您引用的数据库数组,但由于优化,所有字段都将按需加载(CoreData 假设您不会一次使用所有数据)。但是,如果您确定需要某些特定字段(希望避免 SQL 运行另一个请求并赢得几个毫秒),您可以通过此属性指定要预加载的属性。

    绝对不能预加载属于另一个表的字段。

    【讨论】:

    • 如果我反过来搜索Player,我会得到与谓词匹配的所有记录。如果是“播放器”,我使用NSPredicate(format: "ANY %K &gt; 0", #keyPath(Players.playersShiftRelationship.timeOnIce))' and it returns 11 rows, which is great, but I really only need the 'Player' and not every records for timeOnIce`
    • 您要求从 Players 表中预加载 Shifts.playersRelationship 的值。
    • 感谢您的更新。我想我必须采取一些不同的方法。可能有两个查询(子查询)来获得我所追求的。
    猜你喜欢
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多