'to-many key not here here'但为什么?

时间:2017-04-12 14:34:43

标签: ios swift xcode core-data

我正在使用以下实体构建地图应用程序:

enter image description here

enter image description here

协调到地图是一个,地图到坐标是一个多对多的关系。

我的代码是:

 fileprivate var fetchedResultsControllerForMapEntity: NSFetchedResultsController<Map> = {
// Create Fetch Request
let fetchRequest: NSFetchRequest<Map> = Map.fetchRequest()

// Configure Fetch Request
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
fetchRequest.predicate = NSPredicate(format:"newRelationship == %@", "peachesfarm")

// Create Fetched Results Controller
let fetchedResultsControllerForMapEntity = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)

return fetchedResultsControllerForMapEntity
}()

fileprivate var fetchedResultsControllerForCoordinateEntity: NSFetchedResultsController<Coordinate> = {
// Create Fetch Request
let fetchRequest: NSFetchRequest<Coordinate> = Coordinate.fetchRequest()

// Configure Fetch Request
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "latitude", ascending: true)]
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "longitude", ascending: true)]

// Create Fetched Results Controller
let fetchedResultsControllerForCoordinateEntity = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)

return fetchedResultsControllerForCoordinateEntity
}()

我基本上只是试图检索名为“peachesfarm”的地图坐标。为什么我会得到这个例外?

1 个答案:

答案 0 :(得分:1)

NSPredicate(format:"newRelationship == %@", "peachesfarm")

给出错误,因为&#34; newRelationship&#34;是一种多对多的关系,这是一种关系 无法比较平等。

要获取与具有给定名称的地图相关的所有坐标, 你必须使用&#34; Coordinate&#34;的获取请求,而不是&#34; Map&#34;。 然后使用关键路径指向相关地图的名称。使用 由@vadian建议的关系名称将是

let fetchRequest: NSFetchRequest<Coordinate> = Coordinate.fetchRequest()
let predicate = NSPredicate(format: "map.name == %@", "peachesFarm")
fetchRequest.predicate = predicate

更好的是,使用编译器检查的#keyPath指令 属性名称,以避免错误:

let predicate = NSPredicate(format: "\(#keyPath(Coordinate.map.name)) == %@", "peachesFarm")