CoreData方式的数据保存: 一对一
// ViewController.swift
// testOne
//
// Created by Mac on 2022/3/24.
//
importUIKit
importCoreData
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//添加数据
self.addData()
//查询数据
self.queryData()
//修改数据
self.modifyData()
}
//添加数据
funcaddData() {
letapp =UIApplication.shared.delegateas!AppDelegate
letcontext = app.persistentContainer.viewContext
//创建User对象
let user = NSEntityDescription.insertNewObject(forEntityName: "Book",
into: context)as!Book
user.id="0000"
user.name="添加"
//保存
do{
trycontext.save()
print("保存成功")
}catch{
fatalError("不能保存")
}
}
//查询数据
funcqueryData() {
letapp =UIApplication.shared.delegateas!AppDelegate
letcontext = app.persistentContainer.viewContext
//声明数据的请求
letrequest =NSFetchRequest(entityName:"Book")
do{
letfetchedObjects =trycontext.fetch(request)
letname = fetchedObjects.first?.name
letid = fetchedObjects.first?.id
print("one:\(fetchedObjects)")
print("two:\(name)")
print("three:\(id)")
}catch{
fatalError("不能查询")
}
}
//修改数据操作
func modifyData() {
letapp =UIApplication.shared.delegateas!AppDelegate
letcontext = app.persistentContainer.viewContext
//声明数据的请求
letrequest =NSFetchRequest(entityName:"Book")
do{
letfetchedObjects =trycontext.fetch(request)
fetchedObjects.first?.name="修改"
fetchedObjects.first?.id="03"
trycontext.save()
print("\(fetchedObjects)")
}catch{
fatalError("不能修改")
}
}
// 全删
func deleteData() {
letapp =UIApplication.shared.delegateas!AppDelegate
letcontext = app.persistentContainer.viewContext
//声明数据的请求
letrequest =NSFetchRequest(entityName:"Book")
do{
letfetchedObjects =trycontext.fetch(request)
context.delete(fetchedObjects.first!)
try! context.save()
}catch{
fatalError("不能全删除")
}
}
}
网友评论