如何在 swift 中将核心数据管理对象数组转换为 "identifiable" 列表? (Xcode 11,测试版 5)

How to transform array of core data managed objects into an "identifiable" list, in swift? (Xcode 11, Beta 5)

如何将使用 Swift/IOS 通过 "fetchRequest" 从 Core Data 检索到的托管对象数组传输到 "identifiable" 数组?

示例 - 如何制作 "tasks" 数组 "identifiable"

let fetchRequest : NSFetchRequest<Todo> = Todo.fetchRequest()
let tasks = try context?.fetch(fetchRequest)

背景:

使用替换ForEach(Data, id: \.idAttribute)

功能 identified(by: .self) 已替换为新语法:

ForEach(filteredGrapes, id: \.id) { grape in
    GrapeCell(grape: grape)
}

核心数据示例:

将名为 ItemStore.xcdatamodeld 的文件与启用了 Generation=Class Definition 定义的实体 ItemDAO 一起使用,并具有名为 title.

的字符串属性

注意:必须 Product/Clear Build Folder 然后重新启动 Xcode 才能使 Xcode11Beta5 找到正确的密钥路径,这似乎是 Xcode11Beta5 中的一个错误.

import Foundation
import SwiftUI
import CoreData

class MyItemStore {
    public static func defaultItems() -> [ItemDAO]{
        let store = NSPersistentContainer(name: "ItemStore")
        store.loadPersistentStores { (desc, err) in
            if let err = err {
                fatalError("core data error: \(err)")
            }
        }
        let context = store.viewContext
        let item = ItemDAO(context: context)
        item.title = "hello you"
        try! context.save()
        return [
            item,
            item,
        ]
    }
}

struct CoreDataView: View {
    let items: [ItemDAO] = MyItemStore.defaultItems()

    var body: some View {
        VStack{
            ForEach(items, id: \.title) { (item: ItemDAO) in
                Text(item.title ?? "no title")
            }
            Text("hi")
        }
    }
}

通过扩展添加可识别

extension Todo: Identifiable {
    public var id: String {
        //return self.objectID.uriRepresentation().absoluteString
        return self.title!
    }
}

手动维护 CoreData 模型以添加 Identifiable

在那里你可以像往常一样添加 Identifiable,这不是必需的,因为扩展也可以添加 Identifiable。