如何在Swift 4中循环关系

时间:2017-11-05 22:25:59

标签: swift core-data

我们说我有一个阵列' Stores'其中包含来自Core Data数据库的Store实体。

该应用的用户想要查看商店1和商店4的所有商品,因此他选择商店1'并且'存储4'在tableview中。

我现在如何将商店1和商店4中的所有商品放入数组中?

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

第3行打印:

Optional("Store 1")
  

第4行打印:

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'>";
}))
  

第6行打印:

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

我的数据结构:

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

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

==编辑==

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

1 个答案:

答案 0 :(得分:2)

我找到了我在这里寻找的解决方案:CoreData relationship fault?

我不得不改变:

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

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