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框架 数据持久化的更多相关文章

  1. iOS开发网络篇—数据缓存

      iOS开发网络篇—数据缓存 一.关于同一个URL的多次请求 有时候,对同一个URL请求多次,返回的数据可能都是一样的,比如服务器上的某张图片,无论下载多少次,返回的数据都是一样的. 上面的情况会造 ...

  2. 李洪强iOS开发-网络新闻获取数据思路回顾

    李洪强iOS开发-网络新闻获取数据思路回顾 01 创建一个继承自AFHTTPSessionManager的工具类:LHQNetworkTool 用来发送网络请求获取数据  1.1 定义类方法返回单例对 ...

  3. IOS开发UI基础--数据刷新

    IOS开发UI基础--数据刷新 cell的数据刷新包括下面几个方面 加入数据 删除数据 更改数据 全局刷新方法(最经常使用) [self.tableView reloadData]; // 屏幕上的全 ...

  4. iOS中几种数据持久化方案

    概论 所谓的持久化,就是将数据保存到硬盘中,使得在应用程序或机器重启后可以继续访问之前保存的数据.在iOS开发中,有很多数据持久化的方案,接下来我将尝试着介绍一下5种方案: plist文件(属性列表) ...

  5. iOS中几种数据持久化方案:我要永远地记住你!

    http://www.cocoachina.com/ios/20150720/12610.html 作者:@翁呀伟呀 授权本站转载 概论 所谓的持久化,就是将数据保存到硬盘中,使得在应用程序或机器重启 ...

  6. iOS 两行代码解决数据持久化

    在实际的iOS开发中,有些时候涉及到将程序的状态保存下来,以便下一次恢复,或者是记录用户的一些喜好和用户的登录信息等等. 这就需要涉及到数据的持久化了,所谓数据持久化就是数据的本地保存,将数据从内存中 ...

  7. iOS开发,让数据更安全的几个加密方式

    任何应用的开发中安全都是重中之重,在信息交互异常活跃的现在,信息加密技术显得尤为重要.在app应用开发中,我们需要对应用中的多项数据进行加密处理,从而来保证应用上线后的安全性,给用户一个安全保障.这篇 ...

  8. App开发流程之数据持久化和编译静态链接库

    先记录数据持久化. iOS客户端提供的常用数据持久化方案:NSUserDefaults代表的用户设置,NSKeydArchiver代表的归档,plist文件存储,SQLite数据库(包括上层使用的Co ...

  9. iOS开发基础框架

    ---恢复内容开始--- //appdelegate ////  AppDelegate.m//  iOS开发架构////  Copyright © 2016年 Chason. All rights ...

随机推荐

  1. Unity Critter地图导出到server配置

    普通情况下,从Critter导出的地图会与Unity自带的Navigation洪培出的地图会有比較大的差异.须要耐心调整Critter的參数才干够. 以下是我调的參数,与Unity导出的地图基本相似. ...

  2. MySQL InnoDB类型数据库的恢复

     MySQL的数据库文件直接复制便可以使用,但是那是指“MyISAM”类型的表. 而使用MySQL-Front直接创建表,默认是“InnoDB”类型,这种类型的一个表在磁盘上只对应一个“*.frm”文 ...

  3. js加减乘除丢失精度

    js加减乘除(学了那么久现在才注意到汗==!) /** ** 除法函数,用来得到精确的除法结果 ** 说明:javascript的除法结果会有误差,在两个浮点数相除的时候会比较明显.这个函数返回较为精 ...

  4. 如何写好react组件

    react 组件方面: 总结 React 组件的三种写法 及最佳实践 [涨经验] React组件编写思路(一) 使用react-router实现单页面应用时设置页面间过渡的两种方式 [翻译]基于 Cr ...

  5. 织梦首页TAG标签页的仿制

    1,tag标签的作用:主要是为了能够使得用户可以更加精确的找寻到自己所需内容.这种TAG搜索方式,比分类搜索更加的精确.具体以及节省时间. 2,怎么能够合理的优化TAG标签? A:明白网站的TAG标签 ...

  6. Ubuntu linux 返回上一次访问的目录

    cd - (cd空格 减号)返回最近一次访问的目录 这个非常方便.平时经常用终端切换目录,能够方便地回到原来的目录就很爽了. jiqing@jiqing-pad:/usr/local/redis/sr ...

  7. 网页音乐播放器javascript实现,可以显示歌词

    可以显示歌词,但是歌词和歌曲都要实现自己下载下来.只能播放一首歌,歌词还得是lrc格式的代码写的很罗嗦,急切希望帮改改CSS的代码​1.代码:<html >    <head> ...

  8. HDU - 2066 一个人的旅行(最短路径)(模板)

    d.每组的第一行是三个整数T,S和D,表示有T条路,和草儿家相邻的城市的有S个(草儿家到这个城市的距离设为0),草儿想去的地方有D个: 求D个城市中距离草儿家最近的距离. s.进行1次单源最短路,找出 ...

  9. CollectionView缩放水平卡片布局

    实现效果 实现思路 从Demo效果图中,可以看出来,主要是缩放系数的计算.对于不同距离的cell,其缩放系数要变化,以便整体协调显示. 所以,我们必须重写-layoutAttributesForEle ...

  10. P4455 [CQOI2018]社交网络

    这个题仔细一看就是生成树计数,但是我这个记性是真的差,早就忘了.复习了一下高斯消元,然后这个题就是很裸的题了. ps:高斯消元解行列式的时候要取反. 题干: 题目背景 当今社会,在社交网络上看朋友的消 ...