Xcode8,Swift3,CoreData的使用
2016-10-25 本文已影响727人
OSong
<WeChat: sxn8000 文中如有错误望指出>
注意要添加头文件
import coredata
//获得当前应用的AppDelegate对象
let delegate = UIApplication.shared.delegate as! AppDelegate
//MARK: 增加
func insert() {
//Entity实体
let entity = NSEntityDescription.insertNewObject(forEntityName: "Student", into: delegate.persistentContainer.viewContext) as! Student
entity.name = "皮卡丘"
delegate.saveContext()
}
屏幕快照 2016-10-25 下午9.21.16.png
func delete() {
let request: NSFetchRequest<Student> = Student.fetchRequest()
let entity = NSEntityDescription.entity(forEntityName: "Student", in: delegate.persistentContainer.viewContext)
request.entity = entity
let arr = try! delegate.persistentContainer.viewContext.fetch(request)
for stu in arr {
if stu.name == "zhangsan" {
delegate.persistentContainer.viewContext.delete(stu)
try! delegate.persistentContainer.viewContext.save()
}
}
}
屏幕快照 2016-10-25 下午9.21.24.png
func update() {
let request: NSFetchRequest<Student> = Student.fetchRequest()
let entity = NSEntityDescription.entity(forEntityName: "Student", in: delegate.persistentContainer.viewContext)
request.entity = entity
let arr = try! delegate.persistentContainer.viewContext.fetch(request)
let data = arr[3]
data.name = "周杰伦"
try! delegate.persistentContainer.viewContext.save()
}
屏幕快照 2016-10-25 下午9.21.50.png
//MARK: 查找
func fetch() {
let request:NSFetchRequest<Student> = Student.fetchRequest()
let entity = NSEntityDescription.entity(forEntityName: "Student", in: delegate.persistentContainer.viewContext)
request.entity = entity
let arr = try! delegate.persistentContainer.viewContext.fetch(request)
for st in arr {
print(st.name)
}
}
屏幕快照 2016-10-25 下午9.22.14.png