1

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

3
  • You can also set the relationship in the opposite way: itemDetail.invoice = newInovice Feb 6, 2016 at 21:07
  • can you check that you're not adding the same object all over again? I mean, can you check that itemDetail is different from the previous one? Feb 6, 2016 at 21:13
  • I did see it done this way in the docs and have implemented it in my code now. Much cleaner, thanks.
    – R Heffren
    Feb 7, 2016 at 16:33

1 Answer 1

0

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.

1
  • Thank you @Mundi!! That was it! I just moved the line itemDetail = NSEntityDescription.insertNewObjectForEntityForName("InvoiceDetail", inManagedObjectContext: managedObjectContext) as! InvoiceDetailMO into the loop and poof, it's doing what it should.
    – R Heffren
    Feb 7, 2016 at 16:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.