gpt4 book ai didi

swift - 使用@fetchRequest(实体: ) for SwiftUI macOS app crashes

转载 作者:行者123 更新时间:2023-12-02 11:20:34 26 4
gpt4 key购买 nike

我正在尝试使用 Core Data 为 macOS 运行一个基本的测试 SwiftUI 应用程序,但我遇到了一个问题。当我在我看来使用它时:
@FetchRequest(entity: Note.entity(), sortDescriptors: []) let notes: FetchedResults<Note>
该应用程序崩溃并出现以下错误:

NoteTaker [error] error: No NSEntityDescriptions in any model claim the NSManagedObject subclass 'NoteTaker.Note' so +entity is confused.  Have you loaded your NSManagedObjectModel yet ?
CoreData: error: No NSEntityDescriptions in any model claim the NSManagedObject subclass 'NoteTaker.Note' so +entity is confused. Have you loaded your NSManagedObjectModel yet ?

NoteTaker [error] error: +[NoteTaker.Note entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass
CoreData: error: +[NoteTaker.Note entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass

NoteTaker executeFetchRequest:error: A fetch request must have an entity.

现在,如果我使用 FetchRequest 的替代形式,那么它就可以正常工作,尽管代码要丑得多:
// outside of the view
func getAllNotes() -> NSFetchRequest<Note> {
let request: NSFetchRequest<Note> = Note.fetchRequest()
request.sortDescriptors = []
return request
}

// in the view
@FetchRequest(fetchRequest: getAllNotes()) var notes: FetchedResults<Note>

另外,如果我把它变成一个 iOS 应用程序,那么 @FetchRequest 的实体版本就可以正常工作。

有任何想法吗?

最佳答案

我在我的代码中的几个地方收到此错误,用于获取和动态获取请求以及在创建核心数据对象时,这对我有用:
在获取请求期间,我使用了这个:

@FetchRequest(entity: NSEntityDescription.entity(forEntityName: "Your Entity Name", in: managedObjectContext), sortDescriptors: [NSSortDescriptor(key: "Your Key", ascending: true)])
在动态获取请求中,我使用了这个:
var entity: Entity
var fetchRequest: FetchRequest<Your Entity>
init(_ entity: Entity) {
self.entity = entity
self.fetchRequest = FetchRequest(entity: NSEntityDescription.entity(forEntityName: "Your Entity", in: managedObjectContext), sortDescriptors: [NSSortDescriptor(key: "Your Key", ascending: true)], predicate: NSPredicate(format: "entity.uniqueIdentifier == %@", entity.uniqueIdentifier!))
}

var youEntities: FetchedResults<Your Entity> {
fetchRequest.wrappedValue
}
创建核心数据对象时:
let entityDescription = NSEntityDescription.entity(forEntityName: "Your Entity", in: managedObjectContext)

let object = Your Entity(entity: entityDescription!, insertInto: managedObjectContext)

关于swift - 使用@fetchRequest(实体: ) for SwiftUI macOS app crashes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58794088/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com