如何通过CoreData中的关系传递谓词

时间:2018-01-08 17:14:42

标签: swift core-data nsfetchedresultscontroller

我正在尝试让拥有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:'

enter image description here

1 个答案:

答案 0 :(得分:0)

您正在提取玩家,但设置要从转移

获取的属性

修改

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

当然,它无法预加载属于另一个表的字段。