Swift - 使用Core Data进行数据持久化存储

(本文代码升级至Swfit3)

一,Core Data介绍
1,Core Data是iOS5之后才出现的一个数据持久化存储框架,它提供了对象-关系映射(ORM)的功能,即能够将对象转化成数据,也能够将保存在数据库中的数据还原成对象。
2,虽然其底层也是由类似于sql的技术来实现,但我们不需要编写任何sql语句,有点像Java开发中的Hibernate持久化框架
3,Core Data数据最终的存储类型可以是:sqlite数据库,XML,二进制,内存里,或自定义数据类型。
4,与sqlite区别:只能取出整个实体记录,然后分解,之后才能得到实体的某个属性

二,Core Data的使用准备 - 数据模型和实体类的创建
1,创建项目的时候,勾选“ Use Core Data”。完毕后在 AppDelegate中,会生成相关代码


2,打开项目中的 xcdatamodeld文件,在右边的数据模型编辑器的底部工具栏点击 Add Entity添加实体。
同时在属性栏中对实体命名进行修改,并在 Attribute栏目中添加 idusernamepassword三个属性


3,点击下方的 Editor Style按钮可以查看实体的关系图。

4,自 iOS10swift3之后,访问 CoreData方法简洁了许多,我们不再需要手动新建对应于 entityclass

三,Core Data的使用
1,首先在代码中引入CoreData库
1
import CoreData

2,插入(保存)数据操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//获取管理的数据上下文 对象
let app = UIApplication .shared.delegate as ! AppDelegate
context = app.persistentContainer.viewContext
//创建User对象
user = NSEntityDescription .insertNewObject(forEntityName: "User" ,
into: context) User
//对象赋值
user.id = 1
user.username = "hangge"
user.password = "1234"
//保存
do {
try context.save()
print ( "保存成功!" )
} catch {
fatalError( "不能保存:\(error)" )
}

3,查询数据操作
20
21
22
23
24
25
26
27
//声明数据的请求
fetchRequest = NSFetchRequest < User >(entityName: )
fetchRequest.fetchLimit = 10 //限定查询结果的数量
fetchRequest.fetchOffset = 0 //查询的偏移量
//设置查询条件
predicate = nspredicate (format: "id= '1' " ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas, "" )
fetchRequest.predicate = predicate
//查询操作
fetchedobjects = try context.fetch(fetchRequest)
//遍历查询的结果
for info in fetchedobjects{
"id=\(info.id)" )
"username=\(info.username)" )
"password=\(info.password)" )
}
}
catch {
)
}

4,修改数据操作
即将查询出来的对象进行重新赋值,然后再使用context.save方法重新保存即可
1
2
3
4
5
6
7
//遍历查询的结果
for info in fetchedobjects{
info.password = "abcd"
//重新保存
try context.save()
}

5,删除数据操作
删除操作使用context.delete方法删除某个对象。然后使用context.save方法保存更新到数据库
7
8
//删除对象
context.delete(info)
}
//重新保存-更新到数据库
try! context.save()

四,数据的存放位置
认Core Data生成的是sqlite文件,保存在Documents文件夹下


原文出自: www.hangge.com 转载请保留原文链接 http://www.hangge.com/blog/cache/detail_767.html

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...