简体   繁体   中英

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

How would one transfer an array of managed objects retrieved from Core Data using Swift/IOS via a "fetchRequest", to an array that is "identifiable"?

Example - How to make the "tasks" array "identifiable"

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

Background:

  • In SwiftUI using a "List" the array of data you pass to the List needs to be "identifiable".
  • I also note the identified(by: .self) seems to be deprecated.
  • Using (Xcode 11, Beta 5)
  • Currently using xcode's automatic creation of managed objects for the core data entities, so would be nice to stick with this approach

Use replacement ForEach(Data, id: \\.idAttribute)

The feature identified(by: .self) was replaced with the new syntax:

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

Coredata example:

Using a file named ItemStore.xcdatamodeld with an entity ItemDAO defined with Generation=Class Definition enabled and having a String-attribute named title .

Note: One has to Product/Clear Build Folder and afterwards restart Xcode to make Xcode11Beta5 find the proper key path, which seems to be a bug in 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")
        }
    }
}

Adding Identifiable via Extension

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

Maintaining CoreData models manually to add Identifiable

There you can add Identifiable as usual, which is not necessary though since an extension can add Identifiable too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM