swiftcore-datansorderedsetnsmutableorderedset

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


I'm having trouble understanding why my ordered set is only saving 1 entry.

my code is as follows:

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)
    }

I've read through the docs and it seems like I'm doing this correctly but it only adds one entry to the ordered set even though I've iterated through the array of objects.

Here is my debugger showing the entries before they are added and the count of the managed object after adding the objects. debuggerWindow

my relationships are set up as follows: relationships


Solution

  • You are only creating one InvoiceDetail outside your for loop. Obviously, you will have to create one for each detail that is contained in the data array.