Swift: 核心数据问题与多对多关系和 nsmutableOrderedSet ValueForKey

Swift: Core data trouble with to-many relationship and mutableOrderedSetValueForKey

我无法理解为什么我的订单集只保存了 1 个条目。

我的代码如下:

let newInovice = NSEntityDescription.insertNewObjectForEntityForName("Invoice", inManagedObjectContext: managedObjectContext) as! InvoiceMO

let itemDetail = NSEntityDescription.insertNewObjectForEntityForName("InvoiceDetail", inManagedObjectContext: managedObjectContext) as! InvoiceDetailMO

    // Data Entry

    // Add invoice number to Invoice
    newInovice.invoiceNumber = getInvoiceNum()
    newInovice.date = invoiceDate
    // Create mutable set to add details
    for items in details {
        itemDetail.detail = items[PropKeys.itemDescription]
        let item = items[PropKeys.itemPrice] ?? "0"
        let itemDouble = {  return Double(item) ?? 0  }()
        itemDetail.price = itemDouble
        let quantity = items[PropKeys.itemQuantity] ?? "1"
        let quantityInt = {  return Int(quantity) ?? 0  }()
        itemDetail.quantity = quantityInt
        print("This is the item detail before insertion: \(itemDetail)")
        newInovice.mutableOrderedSetValueForKey("invoiceDetails").addObject(itemDetail)
        subtotal += itemDouble * Double(quantityInt)
    }
    print("details.Count = \(details.count)")
    print("Start Mutable  \(newInovice.invoiceDetails?.count) End Mutable Set")


    // Save the Data
    do {
        try newCustomer.managedObjectContext?.save()
    } catch {
        print(error)
    }

我已经通读了文档,看起来我这样做是正确的,但即使我已经遍历了对象数组,它也只向有序集中添加了一个条目。

这是我的调试器,它显示了添加前的条目以及添加对象后托管对象的计数。 debuggerWindow

我的关系设置如下: relationships

您只是在 for 循环之外创建一个 InvoiceDetail。显然,您必须为数据数组中包含的每个详细信息创建一个。