CoreData的使用(二)---增删改查
2017-06-12 本文已影响109人
StoneWing
CoreData是苹果自带的一种持久化数据存储的方式,网上很多人说使用起来麻烦,其实正真使用后发现还是蛮方便的,又是系统自带的,其实我还是蛮推荐使用的
-
添加数据操作
func addDemo() {
let entity: NSEntityDescription = NSEntityDescription.entity(forEntityName: "DemoModel", in: CONTEXT)!
let model = DemoModel(entity: entity, insertInto: CONTEXT)
model.id = "1"
model.title = "数据模型添加数据"
do {
try CONTEXT.save()
}catch {
print("添加数据失败:\(error.localizedDescription)")
}
}
-
删除数据
func deleteDemo() {
let request: NSFetchRequest<DemoModel> = DemoModel.fetchRequest()
do {
let array = try CONTEXT.fetch(request)
for model in array {
CONTEXT.delete(model)
}
try CONTEXT.save()
}catch {
print("删除数据失败\(error.localizedDescription)")
}
}
-
查询数据
func findDemo() {
let request: NSFetchRequest<DemoModel> = DemoModel.fetchRequest()
//条件查询:id==1的数据
let predicate: NSPredicate = NSPredicate(format: "id = %@", "1")
request.predicate = predicate
//排序:根据id来排序
let sort: NSSortDescriptor = NSSortDescriptor(key: "id", ascending: false)
request.sortDescriptors = [sort]
do {
//查询的结果:是个数组
let array = try CONTEXT.fetch(request)
}catch {
print("查询数据失败\(error.localizedDescription)")
}
}
-
更新数据
func updateDemo() {
let request: NSFetchRequest<DemoModel> = DemoModel.fetchRequest()
//条件查询:id==1的数据
let predicate: NSPredicate = NSPredicate(format: "id = %@", "1")
request.predicate = predicate
//排序:根据id来排序
let sort: NSSortDescriptor = NSSortDescriptor(key: "id", ascending: false)
request.sortDescriptors = [sort]
do {
//查询的结果:是个数组
let array = try CONTEXT.fetch(request)
for model in array {
model.title = "更新数据"
}
try CONTEXT.save()
}catch {
print("更新数据失败\(error.localizedDescription)")
}
}