CoreData
快速开始
- 新建Model
- 设置Model
- 新建DataController
准备好Model数据,此时并没有加载
let container = NSPersistentContainer(name: "notify")
加载数据
container.loadPersistentStores{ description, error in
if let error = error {
print("Core Data fail to load, \(error.localizedDescription)")
}
}
import CoreData
import Foundation
class DataController: ObservableObject {
let container = NSPersistentContainer(name: "notify")
init(){
container.loadPersistentStores{ description, error in
if let error = error {
print("Core Data fail to load, \(error.localizedDescription)")
}
}
}
}
- App中绑定
import SwiftUI
@main
struct notifyApp: App {
// 注册生命周期
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
// 绑定CoreData
@StateObject private var dataController = DataController()
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, dataController.container.viewContext)
}
}
}
- View中使用
@FetchRequest(entity: Notify.entity(),sortDescriptors: []) var notifies: FetchedResults<Notify>
保存数据
let notify = Notify(context: moc)
notify.title = "demo Title"
notify.id = UUID()
try? moc.save()
删除数据
offset = 1
let notify = notifies[offset]
moc.delete(notify)
一些报错
Thread 1: "executeFetchRequest:error: A fetch request must have an entity."
在有多个实体的情况下,@FetchRequest
需要注明entity参数使用的是那个entity,只有一个entity的时候可以省略,如下所示。
@FetchRequest(entity: Finance.entity(), sortDescriptors: []) var finance: FetchedResults<Finance>