Swift CoreData 基础向
创建项目使用coredata模版
框架创建
lifetrip.xcdatamodeld
Persistence.swift
使用
lifetrip.xcdatamodeld 添加实体
添加实体
![添加实体](https://cdn.jsdelivr.net/gh/sakiraven/imgs/blog/swiftcoredata xcdatamodeld.png)
- coredata保存与查询
代理注入环境 1
2ContentView()
.environment(\.managedObjectContext, PersistenceController.shared.container.viewContext)
1 | @Environment(\.managedObjectContext) private var viewContext |
1 | private func addItem() { |
- 预览模式
代码 1
2
3
4
5
6
7
8
9
10struct LabelView_Previews: PreviewProvider {
static var previews: some View {
let labelEntity: LabelEntity = { () -> LabelEntity in
let labelEntity = LabelEntity(context: PersistenceController.preview.container.viewContext)
labelEntity.picture = UIImage(named: "nekosensei")!.pngData()
return labelEntity
}()
return LabelCardView(labelEntity: labelEntity)
}
}