前言
最近开发的项目遇到了数据持久化的需求,由于对原生有着特殊偏爱的癖好,首先想了解的便是Core Data,遂就此整理了一下近期所学(基础部分还请自行谷歌),希望可以帮到Core Data的初用者,不足之处还请各路大神多多指点。
Core Data简介
Core Date是ios3.0后引入的数据持久化解决方案,它是是苹果官方推荐使用的,不需要借助第三方框架。Core Date实际上是对SQLite的封装,提供了更高级的持久化方式。在对数据库操作时,不需要使用sql语句,也就意味着即使不懂sql语句,也可以操作数据库中的数据。在iOS10之后,Core Data也是有了不少改进。
一、准备工作
1、创建工程,使用Core Data
2、创建一个Entity,新增一个Person,后面会使用
二、Core Data基本使用
首先:import CoreData
1、获取NSManagerContext
func getObjectContext() -> NSManagedObjectContext {
let delegate = UIApplication.shared.delegate as! AppDelegate
let context = delegate.persistentContainer.viewContext
return context
}
2、增删改查基本使用
- 增加数据
func insertData(name: String, age: String) {
//取得上下文
let context = getObjectContext()
//获取之前创建的Person实体
let entity = NSEntityDescription.entity(forEntityName: "Person", in: context)
//获取托管的person对象
let person = NSManagedObject(entity: entity!, insertInto: context)
//给person添加姓名、年龄
person.setValue(name, forKey: "name")
person.setValue(age, forKey: "age")
//执行存储
do {
try context.save()
//成功
} catch {
print(error)
//失败
}
}
- 删除数据
func removeData(name: String, age: String) {
let context = getObjectContext()
let fetchRequest = NSFetchRequest(entityName: "Person")
//设置查找条件
let condition = "name='\(name)'OR age='\(age)'"
let predicate = NSPredicate(format: condition, "")
fetchRequest.predicate = predicate
do {
let fetchResults = try context.fetch(fetchRequest)
guard fetchResults.count > 0 else {
print("未找到数据")
return
}
for result in fetchResults as! [NSManagedObject] {
context.delete(result)
}
//删除之后不要忘记save
try context.save()
print("删除成功")
} catch {
print(error)
//失败
}
这里的condition
设置了匹配名字或年龄的条件"name='\(name)'OR age='\(age)'"
其他的条件用法:
判断字符串首字母是否为字母
let condition = "SELF MATCHES %@", "^[A-Za-z].+"
比较运算符>,<,==,>=,<=,!=,可用于数值及字符串
let condition = "number > 100"
范围运算符:IN、BETWEEN
let condition = "number BETWEEN {1,5}"`
let condition = "address IN {'shanghai','beijing'}"`
字符串本身:SELF
let condition = "SELF == 'APPLE'"
字符串相关:BEGINSWITH、ENDSWITH、CONTAINS
//包含某个字符串
let condition = "content CONTAINS[cd] 'ang'"
//以某个字符串开头
let condition = "content BEGINSWITH[c] 'sh'"
//以某个字符串结束
let condition = "content ENDSWITH[d] 'ang'"
注:[c]不区分大小写[d]不区分发音符号即没有重音符号[cd]既不区分大小写,也不区分发音符号。
通配符:LIKE
//代表通配符
let condition = "content LIKE[cd] 'er'"
let condition = "content LIKE[cd] '???er'"
正则表达式:MATCHES
//以A开头,e结尾
let regex = "^A.+e$"
let condition = "name MATCHES %@",regex
- 改数据
func updateData(name: String) {
let context = getObjectContext()
let fetchRequest = NSFetchRequest(entityName: "Person")
let condition = "name='\(name)'"
let predicate = NSPredicate(format: condition, "")
fetchRequest.predicate = predicate
do {
let fetchResults = try context.fetch(fetchRequest)
guard fetchResults.count > 0 else {
print("未找到数据")
return
}
for result in fetchResults as! [NSManagedObject] {
result.setValue("Developer", forKey: "name")
}
try context.save()
print("修改成功")
} catch {
print(error)
}
}
此处示例,是通过匹配name
后批量修改为"Developer"
,程序内写死了,只为演示,至于实际中按需求发挥O(∩_∩)O哈哈~
- 查询数据
func queryData() {
let fetchRequest = NSFetchRequest(entityName: "Person")
//此处未设置查询条件,默认取所有数据
do {
let context = getObjectContext()
let fetchResults = try context.fetch(fetchRequest)
for result in fetchResults {
let name = result.value(forKey: "name")!
let age = result.value(forKey: "age")!
print("name: \(name), age: \(age)")
}
//成功
} catch {
print(error)
//失败
}
}
本章Demo下载
以上是本人的一些简单总结,也是刚学,不对之处还请各位看客多多留言指正,再此谢过!后续有时间会继续更新...