如何遍历 Swift 4 中的关系

Kev*_*vin 1 core-data swift

假设我有一个数组“Stores”,其中包含来自 Core Data 数据库的 Store 实体。

该应用程序的用户希望查看商店 1 和商店 4 的所有产品,因此他在 tableview 中选择了“商店 1”和“商店 4”。

我现在如何将商店 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
    }
}
Run Code Online (Sandbox Code Playgroud)

第 3 行打印:

Optional("Store 1")
Run Code Online (Sandbox Code Playgroud)

第 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'>";
}))
Run Code Online (Sandbox Code Playgroud)

第 6 行打印:

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

我的数据结构:

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

"Product"
attributes: "name", "price"
relationships: "stores"
Run Code Online (Sandbox Code Playgroud)

== 编辑 ==

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
}()
Run Code Online (Sandbox Code Playgroud)

Kev*_*vin 6

我在这里找到了我正在寻找的解决方案:CoreData 关系错误?

我不得不改变:

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

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