[英]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"? 如何将使用Swift / IOS通过“ fetchRequest”从“核心数据”中检索到的管理对象数组转移到“可识别”数组中?
Example - How to make the "tasks" array "identifiable" 示例-如何使“任务”数组“可识别”
let fetchRequest : NSFetchRequest<Todo> = Todo.fetchRequest()
let tasks = try context?.fetch(fetchRequest)
Background: 背景:
ForEach(Data, id: \\.idAttribute)
ForEach(Data, id: \\.idAttribute)
The feature identified(by: .self)
was replaced with the new syntax: identified(by: .self)
的功能已被新语法替换:
ForEach(filteredGrapes, id: \.id) { grape in
GrapeCell(grape: grape)
}
Using a file named ItemStore.xcdatamodeld
with an entity ItemDAO
defined with Generation=Class Definition
enabled and having a String-attribute named title
. 使用名为
ItemStore.xcdatamodeld
的文件,该文件的实体ItemDAO
定义为启用了Generation=Class Definition
并具有名为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. 注意:必须先获得
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!
}
}
Identifiable
Identifiable
There you can add Identifiable
as usual, which is not necessary though since an extension can add Identifiable too. 在那里您可以照常添加
Identifiable
,但这不是必需的,尽管扩展名也可以添加Identifiable。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.