iOS开发 - CoreData框架 数据持久化
Core Data
Core Data是iOS5之后才出现的一个框架,它提供了对象-关系映射(ORM)的功能,即能够将OC对象转化成数据,保存在SQLite数据库文件中,也能够将保存在数据库中的数据还原成OC对象。在此数据操作期间,我们不需要编写任何SQL语句,这个有点类似于著名的Hibernate持久化框架,不过功能肯定是没有Hibernate强大的。
传统的数据库要把数据写到数据库,而且要写SQL语句 Core Data 就避免了写SQL语句的麻烦了
CoreData的使用步骤
1.创建模型文件 相当于数据库
2.添加实体 相当表
3.创建实体类 相于模型类
4.生成上下文 关联模型文件生成数据库
5.保存对象到数据库
6.从数据库获取对象
7.更新数据
8.删除数据
1.创建模型文件
所谓的创建模型就是间接生成数据库表
2.添加实体
3.创建实体类
以创建员工实体类为例
生成上下文件 关联模型文件生成数据库
NSManagedObjectContext _context = [[NSManagedObjectContext alloc] init];
// 模型文件
NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
// 持久化存储调度器
NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSLog(@"%@",doc);
NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"];
//数据存储的类型 数据库存储路径
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil];
_context.persistentStoreCoordinator = store;
保存对象到数据库
Employee *employee = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];
employee.name = @"zhangsan";
employee.age = @18;
employee.height = @1.89;
[_context save:nil];
打开CoreData的SQL语句输出开关
1.打开Product,点击EditScheme...
2.点击Arguments,在ArgumentsPassed On Launch中添加2项
1> -com.apple.CoreData.SQLDebug
2> 1
CoreData实例
生成实体类
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@interface Employee : NSManagedObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSNumber * age;
@property (nonatomic, retain) NSNumber * height;
@end
#import "Employee.h"
@implementation Employee
@dynamic name;
@dynamic age;
@dynamic height;
@end
import头文件框架
#import "ViewController.h"
#import <CoreData/CoreData.h>
#import "Employee.h"
@interface ViewController ()
@property(strong,nonatomic)NSManagedObjectContext *context;
@end
CoreData模糊查询
@implementation ViewController
#pragma mark 模糊查询
- (IBAction)likeSearcher:(id)sender {
// 查询
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
// 过滤
// 1.查询以wang开头员工
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name BEGINSWITH %@",@"wang"];
// 2.以si 结尾
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name ENDSWITH %@",@"si"];
// 3.名字包含 g
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name CONTAINS %@",@"g"];
// 4.like 以si结尾
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name like %@",@"li*"];
request.predicate = pre;
//读取信息
NSError *error = nil;
NSArray *emps = [self.context executeFetchRequest:request error:&error];
if (!error) {
NSLog(@"emps: %@",emps);
for (Employee *emp in emps) {
NSLog(@"%@ %@ %@",emp.name,emp.age,emp.height);
}
}else{
NSLog(@"%@",error);
}
}
CoreData 更新数据
#pragma mark 更新员工信息
- (IBAction)updateEmployee:(id)sender {
// 把wangwu的身高更改成 1.7
// 1.查找wangwu
NSArray *emps = [self findEmployeeWithName:@"wangwu"];
// 2.更新身高
if (emps.count == 1) {
Employee *emp = emps[0];
emp.height = @1.7;
}
// 3.同步(保存)到数据
[self.context save:nil];
}
-(NSArray *)findEmployeeWithName:(NSString *)name{
// 1.查找员工
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name=%@",name];
request.predicate = pre;
return [self.context executeFetchRequest:request error:nil];
}
CoreData 删除数据
#pragma mark 删除员工
- (IBAction)deleteEmployee:(id)sender {
[self deleteEmployeeWithName:@"lisi"];
}
-(void)deleteEmployeeWithName:(NSString *)name{
// 删除zhangsan
// 1.查找到zhangsan
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name=%@",name];
request.predicate = pre;
// 2.删除zhangsan
NSArray *emps = [self.context executeFetchRequest:request error:nil];
for (Employee *emp in emps) {
NSLog(@"删除员工的人 %@",emp.name);
[self.context deleteObject:emp];
}
// 3.用context同步下数据库
//所有的操作暂时都是在内存里,调用save 同步数据库
[self.context save:nil];
}
CoreData 查询数据
#pragma mark 读取员工信息
- (IBAction)readEmployee:(id)sender {
//创建一个请求对象 (填入要查询的表名-实体类)
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
// 过滤查询
// 查找张三 并且身高大于1.8
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name=%@ AND height > %@",@"zhangsan",@(1.8)];
// request.predicate = pre;
//排序 以身高进行升序
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
// request.sortDescriptors = @[sort];
// 分页查询 总共13条数据 每页显示5条数据
//第一页的数据
request.fetchLimit = 5;
request.fetchOffset = 10;
//读取信息
NSError *error = nil;
NSArray *emps = [self.context executeFetchRequest:request error:&error];
if (!error) {
NSLog(@"emps: %@",emps);
for (Employee *emp in emps) {
NSLog(@"%@ %@ %@",emp.name,emp.age,emp.height);
}
}else{
NSLog(@"%@",error);
}
}
#pragma mark 添加员工信息
- (IBAction)addEmployee:(id)sender {
// 创建员工
Employee *emp1 = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];
// 设置员工属性
emp1.name = @"lisi";
emp1.age = @28;
emp1.height = @2.10;
//保存 - 通过上下文操作
NSError *error = nil;
[self.context save:&error];
if (!error) {
NSLog(@"success");
}else{
NSLog(@"%@",error);
}
}
CoreData 创建上下文
-(void)setupContext{
// 1.上下文 关联Company.xcdatamodeld 模型文件
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
// 关联模型文件
// 创建一个模型对象
// 传一个nil 会把 bundle下的所有模型文件 关联起来
NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
// 持久化存储调度器
NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
// 存储数据库的名字
NSError *error = nil;
// 获取docment目录
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
// 数据库保存的路径
NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"];
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:&error];
context.persistentStoreCoordinator = store;
self.context = context;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
// 创建员工
for (int i = 0; i < 10; i++) {
Employee *emp1 = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];
// 设置员工属性
emp1.name = [NSString stringWithFormat:@"wangwu %d",i];
emp1.age = @(28 + i);
emp1.height = @2.10;
//保存 - 通过上下文操作
NSError *error = nil;
[self.context save:&error];
if (!error) {
NSLog(@"success");
}else{
NSLog(@"%@",error);
}
}
}
@end
调用
- (void)viewDidLoad {
[super viewDidLoad];
// 创建一个数据库 company.sqlite
// 数据库要一张表 员工表 (name,age,heigt)
// 往数据添加员工信息
// CoreData
[self setupContext];
}
iOS开发 - CoreData框架 数据持久化的更多相关文章
- iOS开发网络篇—数据缓存
iOS开发网络篇—数据缓存 一.关于同一个URL的多次请求 有时候,对同一个URL请求多次,返回的数据可能都是一样的,比如服务器上的某张图片,无论下载多少次,返回的数据都是一样的. 上面的情况会造 ...
- 李洪强iOS开发-网络新闻获取数据思路回顾
李洪强iOS开发-网络新闻获取数据思路回顾 01 创建一个继承自AFHTTPSessionManager的工具类:LHQNetworkTool 用来发送网络请求获取数据 1.1 定义类方法返回单例对 ...
- IOS开发UI基础--数据刷新
IOS开发UI基础--数据刷新 cell的数据刷新包括下面几个方面 加入数据 删除数据 更改数据 全局刷新方法(最经常使用) [self.tableView reloadData]; // 屏幕上的全 ...
- iOS中几种数据持久化方案
概论 所谓的持久化,就是将数据保存到硬盘中,使得在应用程序或机器重启后可以继续访问之前保存的数据.在iOS开发中,有很多数据持久化的方案,接下来我将尝试着介绍一下5种方案: plist文件(属性列表) ...
- iOS中几种数据持久化方案:我要永远地记住你!
http://www.cocoachina.com/ios/20150720/12610.html 作者:@翁呀伟呀 授权本站转载 概论 所谓的持久化,就是将数据保存到硬盘中,使得在应用程序或机器重启 ...
- iOS 两行代码解决数据持久化
在实际的iOS开发中,有些时候涉及到将程序的状态保存下来,以便下一次恢复,或者是记录用户的一些喜好和用户的登录信息等等. 这就需要涉及到数据的持久化了,所谓数据持久化就是数据的本地保存,将数据从内存中 ...
- iOS开发,让数据更安全的几个加密方式
任何应用的开发中安全都是重中之重,在信息交互异常活跃的现在,信息加密技术显得尤为重要.在app应用开发中,我们需要对应用中的多项数据进行加密处理,从而来保证应用上线后的安全性,给用户一个安全保障.这篇 ...
- App开发流程之数据持久化和编译静态链接库
先记录数据持久化. iOS客户端提供的常用数据持久化方案:NSUserDefaults代表的用户设置,NSKeydArchiver代表的归档,plist文件存储,SQLite数据库(包括上层使用的Co ...
- iOS开发基础框架
---恢复内容开始--- //appdelegate //// AppDelegate.m// iOS开发架构//// Copyright © 2016年 Chason. All rights ...
随机推荐
- 谈谈TensorFlow with CPU support or TensorFlow with GPU support(图文详解)
不多说,直接上干货! You must choose one of the following types of TensorFlow to install: TensorFlow with CPU ...
- iOS视频流开发(2) — 视频播放
iOS视频流开发(2) — 视频播放 承上篇,本篇文章主要介绍iOS视频播放需要用到的类.以及他们的使用场景和开发中遇到的问题. MPMoviePlayerViewController MP简介 i ...
- Android之——AIDL深入
转载请注明出处:http://blog.csdn.net/l1028386804/article/details/47071927 在上一篇博文<Android之--AIDL小结>中,我们 ...
- web 界面设计---大道至简
http://www.cnblogs.com/coder2012/p/4023442.html 一个非常精简的webpy页面博客 qing.weibo.com 新浪的轻微博也不错精简
- Koa2学习(三)GET请求
Koa2学习(三)GET请求 GET请求是前后端交互最常用的请求之一,常常用来进行查询操作. 那么Koa是如何接收并处理GET请求呢? 创建一个服务 // 引入Koa const Koa = requ ...
- (6)servlet-创建一个servlet类
1,在项目的src目录下,右键[New]-[Servlet] 2,在弹出窗口中填写信息 Package:所在包名 Name:servlet的类名 Which method stubs would yo ...
- CRM 插件奇怪的报错
CRM插件,数据库方式注册.报错 找不到方法:“Void Microsoft.Xrm.Sdk.Entity..ctor(System.String, System.Guid)”. 这个错误让人摸不着头 ...
- shell网络管理
背景知识 联网就是通过网络将主机进行互联并采用不同的规范配置网络上的节点.我们以 TCP/IP 作为网络栈,所有的操作都是基于它进行的.网络是计算机系统中重要的部分.连接在网络上的每个节点都分配了一个 ...
- 小幻美图 API
『不忘初心,方得始终.』 小幻美图 API 更新:2015.03.29 目前提供的API共有10种! 必应各种今日获取API共4种! 本站收录图片获取API共4种! 网络图片尺寸修改API共1枚! 百 ...
- jfreechart应用3--饼状图 学习(作者:百度 被风吹过的日子)
jfreechart应用3--饼状图 三. 饼图 在WebRoot目录下建立名为pie的子目录,用来存放本教程中饼图的实例jsp页面.下面让我们来看一个简单的三维饼图.首先在pie目录下建立一个名为s ...