今天要用SwiftUI做一个简单的CoreData增删查改练习
先做增加(Create)和查看(Read),成品如下: 截屏2020-04-23下午7.13.18.png点击添加的时候会把数据永久存入实体中,这样下一次打开App的时候数据还是在的
首先我们写了一个简单的TextField和一个Button,定义了newPotatoString为输入的内容,一个实体Entity为Potato 和一个键,OK那我们直接上代码吧
//Create
func addNewPotato(){
guard let appDelegate =
UIApplication.shared.delegate as? AppDelegate else{
return
}
//存放数据
let managedContext =
appDelegate.persistentContainer.viewContext
//声明在那个实体中 Potato
let entity =
NSEntityDescription.entity(forEntityName:"Potato",
in: managedContext)!
//声明一个新的实例 newPotato
let newPotato =NSManagedObject(entity: entity,
insertInto: managedContext)
//设置值 将newPotatoString的值wrappedValue打包后设置到stringAttribute中
newPotato.setValue($newPotatoString.wrappedValue, forKeyPath:"stringAttribute")
do{
try managedContext.save()
print("saved successfully --\($newPotatoString.wrappedValue)")
self.loadPotatos()
}catch let error as NSError{
print("Could not save. \(error), \(error.userInfo)")
}
}
//Read
func loadPotatos(){
guard let appDelegate =
UIApplication.shared.delegate as? AppDelegate else{
return
}
let managedContext =
appDelegate.persistentContainer.viewContext
let fetchRequest =
NSFetchRequest<NSManagedObject>(entityName: "Potato")
do{
potatoes=try managedContext.fetch(fetchRequest)
self.showSheet=false
}catch let error as NSError{
print("Could not fetch. \(error), \(error.userInfo)")
}
}
网友评论