Dea*_*ano 8 macos core-data swift swiftui
我正在尝试使用 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.
Run Code Online (Sandbox Code Playgroud)
现在,如果我使用 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>
Run Code Online (Sandbox Code Playgroud)
另外,如果我把它变成一个 iOS 应用程序,那么 @FetchRequest 的实体版本就可以正常工作。
有任何想法吗?
小智 -1
使用Storyboard 模板,然后在视图控制器中使用 SwiftUI 设置视图。
override func viewWillAppear() {
super.viewWillAppear()
let context = (NSApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let contentView = ContentView().environment(\.managedObjectContext, context)
view = NSHostingView(rootView: contentView)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1626 次 |
| 最近记录: |