【问题标题】:How to loop through a relationship in Swift 4如何在 Swift 4 中循环关系
【发布时间】:2018-04-18 01:07:33
【问题描述】:

假设我有一个数组“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
    }
}

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

【问题讨论】:

  • 你想形成的数组在哪里?我在您的代码中的任何地方都看不到任何数组。但无论如何,在您获取产品之前,什么都不会发生。现在,他们正在犯错。你不应该循环;您应该构建一个获取所有选定商店的产品的 fetch。
  • 我已经添加了您要求的代码。但我自己也找到了解决方案(见下面的答案)。不过,您提到我不应该遍历这些关系,这是为什么呢?

标签: swift core-data


【解决方案1】:

我在这里找到了我正在寻找的解决方案: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!)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-13
    • 1970-01-01
    • 2018-08-15
    • 2016-03-28
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2016-07-26
    相关资源
    最近更新 更多