我试图获得一个账单的总价格,该账单中有许多与coredata相关的项目。我正在努力理解检索项目所需的谓词语法,以便我可以访问它们的价格。我一直收到以下错误:
2016-12-14 14:13:12.309 Splitter[43533:5597917] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'unimplemented SQL generation for predicate : (ANY items IN <Splitter.Bill: 0x7fe6e0cebbd0> (entity: Bill; id: 0xd000000000300000 <x-coredata://D13BAFFD-A78A-4C49-9992-F975887B7AB7/Bill/p12> ; data: {
date = "December 14, 2016";
id = "6D672183-44C2-4961-ABB6-27FD657E5C68";
items = (
"0xd000000001fc0012 <x-coredata://D13BAFFD-A78A-4C49-9992-F975887B7AB7/Item/p127>",
"0xd0000000020c0012 <x-coredata://D13BAFFD-A78A-4C49-9992-F975887B7AB7/Item/p131>",
"0xd000000002080012 <x-coredata://D13BAFFD-A78A-4C49-9992-F975887B7AB7/Item/p130>",
"0xd000000002100012 <x-coredata://D13BAFFD-A78A-4C49-9992-F975887B7AB7/Item/p132>",
"0xd000000002040012 <x-coredata://D13BAFFD-A78A-4C49-9992-F975887B7AB7/Item/p129>",
"0xd000000001f00012 <x-coredata://D13BAFFD-A78A-4C49-9992-F975887B7AB7/Item/p124>",
"0xd000000001f80012 <x-coredata://D13BAFFD-A78A-4C49-9992-F975887B7AB7/Item/p126>",
"0xd000000001e80012 <x-coredata://D13BAFFD-A78A-4C49-9992-F975887B7AB7/Item/p122>",
"0xd000000001f40012 <x-coredata://D13BAFFD-A78A-4C49-9992-F975887B7AB7/Item/p125>",
"0xd000000001ec0012 <x-coredata://D13BAFFD-A78A-4C49-9992-F975887B7AB7/Item/p123>",
"(...and 1 more...)"
);
location = hgfhgfd;
name = hgfhgfd;
total = 0;
}))'
从以下代码:
func setBillTotal() {
let managedContext = billObject.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Item")
let predicate = NSPredicate(format: "ANY items IN %@", billObject)
fetchRequest.predicate = predicate
var items = [Item]()
do {
let results =
try managedContext!.executeFetchRequest(fetchRequest)
items = results as! [Item]
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
var sum = Int(0.0)
for item in items {
sum += Int(item.price)
}
billObject.setValue(sum, forKey: "total")
do {
try managedContext!.save()
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}
任何帮助都会很棒,我确定它只是一个简单的修复,但语法在我的脑海中浮现。感谢
答案 0 :(得分:1)
直接的答案是你应该在你的谓词中使用反向关系bill
:
let predicate = NSPredicate(format: "bill == %@", billObject)
但是,有一种更简单的方法可以实现计算总价格的目标:
let total = billObject.valueForKeyPath("items.@sum.price")
billObject.setValue(total, forKey:"total")
不需要获取请求,也不需要for循环遍历项目:这两行将实现相同的目标。