Kevin
Kevin

Reputation: 3150

How to loop through a relationship in Swift 4

Let's say that I have an array 'Stores' which contains Store entities from a Core Data database.

The user of the app wants to see all products of store 1 and 4, so he selects 'store 1' and 'store 4' in the tableview.

How can I now put all the products from store 1 and store 4 in an array?

for store in selectedStores {
    let products = store.products
    print(store.name) // line3
    print(store.products) // line4
    for product in products! {
        print("\(product)") // line6
    }
}

Line 3 prints:

Optional("Store 1")

Line 4 prints:

Optional(Relationship 'products' fault on managed object (0x1c0097610) <__App.Store: 0x1c0097610> (entity: Store; id: 0xd00000000004000a <x-coredata://8777A8A9-3416-4525-9246-509B9070D222/Store/p1> ; data: {
    name = Store 1;
    products = "<relationship fault: 0x1c02283a0 'products'>";
}))

Line 6 prints:

<__App.Product: 0x1c4090040> (entity: Product; id: 0xd00000000004000c <x-coredata://8777A8A9-3416-4525-9246-509B9070D222/Product/p1> ; data: <fault>)

My datastructure:

"Store"
attributes: "name"
relationships: "products"

"Product"
attributes: "name", "price"
relationships: "stores"

== Edit ==

var selectedStores: [Store] = []

fileprivate lazy var fetchedResultsController: NSFetchedResultsController<Store> = {
    let fetchRequest: NSFetchRequest<Store> = Store()
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
    let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.persistentContainer.viewContext, sectionNameKeyPath: nil, cacheName: nil)
    fetchedResultsController.delegate = self
    return fetchedResultsController
}()

Upvotes: 1

Views: 1983

Answers (1)

Kevin
Kevin

Reputation: 3150

I have found the solution where I was looking for here: CoreData relationship fault?

I had to change:

for store in selectedStores {
    let products = store.products
    print(store.name) // line3
    print(store.products) // line4
    for product in products! {
        print("\(product)") // line6
    }
}

to

for store in selectedStores {
    for product in store.products?.allObjects as! [Product] {
        print(product.name!)
    }
}

Upvotes: 6

Related Questions