谓词匹配一对多关系核心数据

Waz*_*zza 0 core-data ios swift

我正在尝试获取在 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;
    }))'
Run Code Online (Sandbox Code Playgroud)

从以下代码:

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)")
    }
}
Run Code Online (Sandbox Code Playgroud)

数据库关系图: 物品 账单

任何帮助都会很棒,我确信它是一个简单的修复,但语法在某处超出了我的头脑。谢谢

pba*_*sdf 5

直接的答案是您应该bill在谓词中使用逆关系 , :

let predicate = NSPredicate(format: "bill == %@", billObject)
Run Code Online (Sandbox Code Playgroud)

但是,有一种更简单的方法可以实现计算总价的目标:

let total = billObject.valueForKeyPath("items.@sum.price")
billObject.setValue(total, forKey:"total")
Run Code Online (Sandbox Code Playgroud)

不需要 fetch 请求,也不需要 for 循环遍历项目:这两行将实现相同的效果。