一、概念
1.Core Data 是数据持久化存储的最佳方式
2.数据最终的存储类型可以是:SQLite数据库,XML,二进制,内存里,或自定义数据类型
在Mac OS X 10.5Leopard及以后的版本中,开发者也可以通过继承NSPersistentStore类以创建自定义的存储格式
3.好处:能够合理管理内存,避免使用sql的麻烦,高效
4.构成:
(1)NSManagedObjectContext(被管理的数据上下文)
操作实际内容(操作持久层)
作用:插入数据,查询数据,删除数据
(2)NSManagedObjectModel(被管理的数据模型)
数据库所有表格或数据结构,包含各实体的定义信息
作用:添加实体的属性,建立属性之间的关系
操作方法:视图编辑器,或代码
(3)NSPersistentStoreCoordinator(持久化存储助理)
相当于数据库的连接器
作用:设置数据存储的名字,位置,存储方式,和存储时机
(4)NSManagedObject(被管理的数据记录)
相当于数据库中的表格记录
(5)NSFetchRequest(获取数据的请求)
相当于查询语句
(6)NSEntityDescription(实体结构)
相当于表格结构
(7)后缀为.xcdatamodeld的包
里面是.xcdatamodel文件,用数据模型编辑器编辑
编译后为.momd或.mom文件
5.依赖关系 http://pic002.cnblogs.com/images/2012/373740/2012100910564755.png
二、基于SQLite数据库时,Core Data的简单使用
和SQLite的区别:只能取出整个实体记录,然后分解,之后才能得到实体的某个属性
提供context对象 NSManagedObjectContext:负责用户与数据之间的交互 persistentContainer:存储器,更新CoreD(表)
func getContext() -> NSManagedObjectContext {
let delegate = UIApplication.shared.delegate as! AppDelegate
let context = delegate.persistentContainer.viewContext
return context
}
继承 CoreData
import CoreData
1.创建一个实体描述
//1.2创建一个实体描述
let entityDes = NSEntityDescription.entity(forEntityName: "Student", in: self.getContext())
//1.1创建Student
let st = NSManagedObject(entity: entityDes!, insertInto: self.getContext())
//1.3给student赋值 kvc
st.setValue(10, forKey: "age")
st.setValue("小王", forKey: "name")
//1.4保存对象
try! self.getContext().save()
print(NSTemporaryDirectory())
查询
//1.查那张表
let resquest = NSFetchRequest(entityName: "Student")
//2.执行查找
let arr = try! self.getContext().fetch(resquest) as![NSObject]
//3.查找条件format:谓词(放>,< =,)
let predicate = NSPredicate(format: "name = '小李'", argumentArray: nil)
resquest.predicate = predicate
//2.1执行查找
for item in arr {
let name = item.value(forKey: "name")
let age = item.value(forKey: "age")
try! self.getContext().save()
print("name = \(name) age = \(age)")
}
//4.排序
let sort = NSSortDescriptor(key: "age", ascending: true)
resquest.sortDescriptors = [sort]
//5.分页
resquest.fetchOffset = 1
resquest.fetchLimit = 2
//6.更新,修改
item.setValue("小李", forKey: "name")
//删除
self.getContext().delete(item as! NSManagedObject)
CoreData 多个教师 和 多个学生的 关系
import UIKit
import CoreData
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//1.2
let des = NSEntityDescription.entity(forEntityName: "Student", in: self.getContext())
//1.1
let student = NSManagedObject(entity: des!, insertInto: self.getContext())
//1.3
student.setValue("小王", forKey: "name")
student.setValue(12, forKey: "idCard")
let student1 = NSManagedObject(entity: des!, insertInto: self.getContext())
student1.setValue("小王1", forKey: "name")
student1.setValue(22, forKey: "idCard")
//2.2
let teDes = NSEntityDescription.entity(forEntityName: "Teacher", in: self.getContext())
//2.1
let teacher = NSManagedObject(entity: teDes!, insertInto: self.getContext())
//2.3
teacher.setValue("老王", forKey: "name")
teacher.setValue(12, forKey: "age")
let teacher1 = NSManagedObject(entity: teDes!, insertInto: self.getContext())
teacher1.setValue("老王1", forKey: "name")
teacher1.setValue(34, forKey: "age")
//3.1
var set = Set() //定义集合
set.insert(student)
set.insert(student1)
teacher.setValue(set, forKey: "students")
var stSet = Set() //定义集合
stSet.insert(teacher)
stSet.insert(teacher1)
student.setValue(stSet, forKey: "teachers")
try! self.getContext().save()
print(NSTemporaryDirectory())//打印沙盒路径
//查找teacher的学生都叫啥
let request = NSFetchRequest(entityName:"Teacher")
//查找
let pre = NSPredicate(format: "name='老王'", argumentArray: nil)
request.predicate = pre
//执行查找
let arr = try! self.getContext().fetch(request) as! [NSManagedObject]
for item in arr {//获取每一个老师
let set = item.value(forKey: "students") as! Set
for stu in set {
print("老王的学生的名字 \(stu.value(forKey: "name"))")
// item.setValue("老王", forKey: "name")
// print(item)
}
}
}
func getContext() ->NSManagedObjectContext{
let delegate = UIApplication.shared.delegate as! AppDelegate
let context = delegate.persistentContainer.viewContext
return context
}
}