1>什么是CoreData

Core Data是iOS5之后才出现的一个框架,它提供了对象-关系映射(ORM)的功能,即能够将OC对象转化成数据,保存在SQLite数据库文件中,也能够将保存在数据库中的数据还原成OC对象。在此数据操作期间,我们不需要编写任何SQL语句,这个有点类似于著名的Hibernate持久化框架,不过功能肯定是没有Hibernate强大的。
 
 
 
2>CoreData的使用步骤
 
1.创建模型文件
2.添加实体
3.创建实体类
4.生成上下文 关联模型文件生成数据库
5.保存对象到数据库
6.从数据库获取对象
7.更新数据
8.删除数据
 
3>打开CoreData的SQL语句输出开关
 
1.打开Product,点击EditScheme...
2.点击Arguments,在ArgumentsPassed On Launch中添加2项
   1> -com.apple.CoreData.SQLDebug
   2> 1
 

一、CoreData基本使用-增删改查和表关联

  1. //
  2. // ViewController.m
  3. // IOS_0121_CoreData
  4. //
  5. // Created by ma c on 16/1/21.
  6. // Copyright © 2016年 博文科技. All rights reserved.
  7. //
  8.  
  9. #import "ViewController.h"
  10. #import <CoreData/CoreData.h>
  11. #import "Employee.h"
  12. #import "Department.h"
  13.  
  14. @interface ViewController ()
  15.  
  16. @property (nonatomic, strong) NSManagedObjectContext *context;
  17.  
  18. @end
  19.  
  20. @implementation ViewController
  21.  
  22. - (void)viewDidLoad {
  23. [super viewDidLoad];
  24. //1.创建模型文件(相当于数据库中的表)
  25. //2.添加实体(一张表)
  26. //3.创建实体类(相当于模型)
  27. //4.生成上下文,关联模型文件生成数据库
  28.  
  29. //上下文
  30. self.context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
  31. //模型数据文件
  32. NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
  33.  
  34. //持久化存储器
  35. //把数据保存到一个文件,而不是内存
  36. NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
  37. //数据名字和路径
  38. NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
  39. NSString *sqlitePath = [path stringByAppendingPathComponent:@"company.sqlite"];
  40. NSLog(@"%@",sqlitePath);
  41.  
  42. NSURL *url = [NSURL fileURLWithPath:sqlitePath];
  43. [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:nil];
  44.  
  45. self.context.persistentStoreCoordinator = store;
  46.  
  47. }
  48. //数据库操作ADUQ (ADD、Delete、Update、Query)
  49. #pragma mark - 添加员工
  50. - (IBAction)addEmployee
  51. {
  52. Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];
  53.  
  54. emp.name = @"bowen";
  55. emp.height = @"";
  56. emp.birthday = [NSDate date];
  57.  
  58. //直接保存
  59. NSError *error = nil;
  60. [self.context save:&error];
  61.  
  62. if (error) {
  63. NSLog(@"%@",error);
  64. }
  65. }
  66.  
  67. #pragma mark - 查询员工
  68. - (IBAction)searchEmployee
  69. {
  70. //1.NSFetchRequest 抓取请求对象
  71. NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
  72. //2.设置过滤条件
  73. NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"bowen"];
  74. request.predicate = pre;
  75. //3.排序
  76. NSSortDescriptor *heightSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:YES];
  77. request.sortDescriptors = @[heightSort];
  78. //4.执行请求
  79. NSError *error = nil;
  80. NSArray *emps = [self.context executeFetchRequest:request error:&error];
  81.  
  82. if (error) {
  83. NSLog(@"%@",error);
  84. }
  85.  
  86. for (Employee *emp in emps) {
  87. NSLog(@"name:%@ height:%@ birthday:%@",emp.name, emp.height, emp.birthday);
  88. }
  89. }
  90.  
  91. #pragma mark - 更新员工
  92. - (IBAction)updateEmployee
  93. {
  94. //1.查找
  95. //获取对象
  96. NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
  97. //设置过滤条件
  98. NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"bowen"];
  99. request.predicate = pre;
  100. //执行请求
  101. NSArray *emps = [self.context executeFetchRequest:request error:nil];
  102.  
  103. //2.更新
  104. for (Employee *emp in emps) {
  105. emp.height = @"";
  106. }
  107. //3.保存
  108. [self.context save:nil];
  109. }
  110.  
  111. #pragma mark - 删除员工
  112. - (IBAction)deleteEmployee
  113. {
  114. //1.查找
  115. //获取对象
  116. NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
  117. //设置过滤条件
  118. NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"bowen"];
  119. request.predicate = pre;
  120. //执行请求
  121. NSArray *emps = [self.context executeFetchRequest:request error:nil];
  122.  
  123. //2.删除
  124. for (Employee *emp in emps) {
  125. [self.context deleteObject:emp];
  126. }
  127.  
  128. //3.保存
  129. [self.context save:nil];
  130. }
  131.  
  132. #pragma mark - 表关联
  133. - (IBAction)AddRelationship
  134. {
  135. //创建两个部门:IOS、Android
  136. Department *IOSDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:self.context];
  137. IOSDepart.departNo = @"";
  138. IOSDepart.name = @"IOS";
  139. IOSDepart.createDate = [NSDate date];
  140.  
  141. Department *AndroidDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:self.context];
  142. AndroidDepart.departNo = @"";
  143. AndroidDepart.name = @"Android";
  144. AndroidDepart.createDate = [NSDate date];
  145.  
  146. //创建两个员工:bowen1,bowen2
  147. Employee *emp1 = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];
  148. emp1.name = @"bowen1";
  149. emp1.height = @"";
  150. emp1.birthday = [NSDate date];
  151. emp1.depart = IOSDepart;
  152.  
  153. Employee *emp2 = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];
  154. emp2.name = @"bowen2";
  155. emp2.height = @"";
  156. emp2.birthday = [NSDate date];
  157. emp2.depart = AndroidDepart;
  158.  
  159. //保存
  160. [self.context save:nil];
  161. }
  162.  
  163. - (IBAction)searchRelationship
  164. {
  165. //读取IOS部门员工
  166.  
  167. //1.NSFetchRequest 抓取请求对象
  168. NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
  169. //2.设置过滤条件
  170. NSPredicate *pre = [NSPredicate predicateWithFormat:@"depart.name = %@",@"IOS"];
  171. request.predicate = pre;
  172. //3.执行请求
  173. NSError *error = nil;
  174. NSArray *emps = [self.context executeFetchRequest:request error:&error];
  175.  
  176. if (error) {
  177. NSLog(@"%@",error);
  178. }
  179.  
  180. for (Employee *emp in emps) {
  181. NSLog(@"name:%@ height:%@ birthday:%@",emp.name, emp.height, emp.birthday);
  182. }
  183.  
  184. }
  185.  
  186. - (void)didReceiveMemoryWarning {
  187. [super didReceiveMemoryWarning];
  188. // Dispose of any resources that can be recreated.
  189. }
  190.  
  191. @end

三、分页查询和模糊查询

  1. //
  2. // ViewController.m
  3. // IOS_0121_CoreData
  4. //
  5. // Created by ma c on 16/1/21.
  6. // Copyright © 2016年 博文科技. All rights reserved.
  7. //
  8.  
  9. #import "ViewController.h"
  10. #import <CoreData/CoreData.h>
  11. #import "Employee.h"
  12. #import "Department.h"
  13.  
  14. @interface ViewController ()
  15.  
  16. @property (nonatomic, strong) NSManagedObjectContext *context;
  17.  
  18. @end
  19.  
  20. @implementation ViewController
  21.  
  22. - (void)viewDidLoad {
  23. [super viewDidLoad];
  24. //1.创建模型文件(相当于数据库中的表)
  25. //2.添加实体(一张表)
  26. //3.创建实体类(相当于模型)
  27. //4.生成上下文,关联模型文件生成数据库
  28.  
  29. //上下文
  30. self.context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
  31. //模型数据文件
  32. NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
  33.  
  34. //持久化存储器
  35. //把数据保存到一个文件,而不是内存
  36. NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
  37. //数据名字和路径
  38. NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
  39. NSString *sqlitePath = [path stringByAppendingPathComponent:@"company.sqlite"];
  40. NSLog(@"%@",sqlitePath);
  41.  
  42. NSURL *url = [NSURL fileURLWithPath:sqlitePath];
  43. [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:nil];
  44.  
  45. self.context.persistentStoreCoordinator = store;
  46.  
  47. }
  48. //数据库操作ADUQ (ADD、Delete、Update、Query)
  49. #pragma mark - 添加员工
  50. - (IBAction)addEmployee
  51. {
  52.  
  53. for (int i = ; i < ; i++) {
  54. Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];
  55. emp.name = [NSString stringWithFormat:@"bowen%d",i];
  56. emp.height = [NSString stringWithFormat:@"%d",+i];
  57. emp.birthday = [NSDate date];
  58.  
  59. }
  60.  
  61. //直接保存
  62. NSError *error = nil;
  63. [self.context save:&error];
  64.  
  65. if (error) {
  66. NSLog(@"%@",error);
  67. }
  68. }
  69.  
  70. #pragma mark - 分页查询
  71. - (IBAction)pagingAndQuerying
  72. {
  73. //1.NSFetchRequest 抓取请求对象
  74. NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
  75.  
  76. //2.排序
  77. NSSortDescriptor *heightSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:YES];
  78. request.sortDescriptors = @[heightSort];
  79.  
  80. //3.分页查询
  81. //分页的起始索引
  82. request.fetchOffset = ;
  83. //分页的条数
  84. request.fetchLimit = ;
  85.  
  86. //4.执行请求
  87. NSError *error = nil;
  88. NSArray *emps = [self.context executeFetchRequest:request error:&error];
  89.  
  90. if (error) {
  91. NSLog(@"%@",error);
  92. }
  93.  
  94. for (Employee *emp in emps) {
  95. NSLog(@"name:%@ height:%@ birthday:%@",emp.name, emp.height, emp.birthday);
  96. }
  97. }
  98.  
  99. - (IBAction)fuzzyQuery
  100. {
  101. //1.NSFetchRequest 抓取请求对象
  102. NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
  103.  
  104. //2.排序
  105. NSSortDescriptor *heightSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:YES];
  106. request.sortDescriptors = @[heightSort];
  107.  
  108. //3.模糊查询
  109. //名字以“bowen1”开头
  110. //NSPredicate *pre = [NSPredicate predicateWithFormat:@"name BEGINSWITH %@",@"bowen1"];
  111. //request.predicate = pre;
  112.  
  113. //名字以“1”结尾
  114. //NSPredicate *pre = [NSPredicate predicateWithFormat:@"name ENDSWITH %@",@"1"];
  115. //request.predicate = pre;
  116.  
  117. //名字包含“wen1”结尾
  118. //NSPredicate *pre = [NSPredicate predicateWithFormat:@"name CONTAINS %@",@"1"];
  119. //request.predicate = pre;
  120.  
  121. //like
  122. //名字以“1”结尾
  123. //NSPredicate *pre = [NSPredicate predicateWithFormat:@"name like %@",@"*wen14"];
  124. //request.predicate = pre;
  125.  
  126. //名字以“bowen2”开头
  127. NSPredicate *pre = [NSPredicate predicateWithFormat:@"name like %@",@"bowen2*"];
  128. request.predicate = pre;
  129.  
  130. //4.执行请求
  131. NSError *error = nil;
  132. NSArray *emps = [self.context executeFetchRequest:request error:&error];
  133.  
  134. if (error) {
  135. NSLog(@"%@",error);
  136. }
  137.  
  138. for (Employee *emp in emps) {
  139. NSLog(@"name:%@ height:%@ birthday:%@",emp.name, emp.height, emp.birthday);
  140. }
  141. }
  142.  
  143. @end

三、创建多个数据库

  1. //
  2. // ViewController.m
  3. // IOS_0121_CoreData
  4. //
  5. // Created by ma c on 16/1/21.
  6. // Copyright © 2016年 博文科技. All rights reserved.
  7. //
  8.  
  9. #import "ViewController.h"
  10. #import <CoreData/CoreData.h>
  11. #import "Employee.h"
  12. #import "Status.h"
  13.  
  14. @interface ViewController ()
  15.  
  16. @property (nonatomic, strong) NSManagedObjectContext *companyContext;
  17. @property (nonatomic, strong) NSManagedObjectContext *weibocontext;
  18.  
  19. @end
  20.  
  21. @implementation ViewController
  22.  
  23. - (void)viewDidLoad {
  24. [super viewDidLoad];
  25.  
  26. //一个数据库对应着一个上下文
  27. self.companyContext = [self setupContextWithModelName:@"Company"];
  28. self.weibocontext = [self setupContextWithModelName:@"weibo"];
  29.  
  30. }
  31.  
  32. //根据模型文件返回上下文
  33. - (NSManagedObjectContext *)setupContextWithModelName:(NSString *)modelName
  34. {
  35. //1.创建模型文件(相当于数据库中的表)
  36. //2.添加实体(一张表)
  37. //3.创建实体类(相当于模型)
  38. //4.生成上下文,关联模型文件生成数据库
  39.  
  40. //上下文
  41. NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
  42.  
  43. //模型数据文件
  44. //使用下面的方法,如果boundles为空,会把boundles里面所有的模型文件的表都放在一个数据库中
  45. //NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
  46.  
  47. NSLog(@"%@",[[NSBundle mainBundle] bundlePath]);
  48.  
  49. NSURL *modelURL = [[NSBundle mainBundle] URLForResource:modelName withExtension:@"momd"];
  50. NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
  51.  
  52. //持久化存储器
  53. //把数据保存到一个文件,而不是内存
  54. NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
  55.  
  56. //数据名字和路径
  57. NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
  58.  
  59. NSString *sqlliteName = [NSString stringWithFormat:@"%@.sqllite",modelName];
  60.  
  61. NSString *sqlitePath = [path stringByAppendingPathComponent:sqlliteName];
  62. NSLog(@"%@",sqlitePath);
  63.  
  64. NSURL *url = [NSURL fileURLWithPath:sqlitePath];
  65. [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:nil];
  66.  
  67. context.persistentStoreCoordinator = store;
  68.  
  69. return context;
  70.  
  71. }
  72. //数据库操作ADUQ (ADD、Delete、Update、Query)
  73. #pragma mark - 添加
  74. - (IBAction)add
  75. {
  76. Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.companyContext];
  77. emp.name = @"bowen";
  78. emp.height = @"";
  79. emp.birthday = [NSDate date];
  80.  
  81. Status *status = [NSEntityDescription insertNewObjectForEntityForName:@"Status" inManagedObjectContext:self.weibocontext];
  82. status.text = @"回家";
  83. status.createDate = @"2015-01-28";
  84.  
  85. [self.companyContext save:nil];
  86. [self.weibocontext save:nil];
  87.  
  88. }
  89.  
  90. #pragma mark - 查询
  91. - (IBAction)querying
  92. {
  93.  
  94. }
  95.  
  96. @end

IOS-CoreData(增删改查、表关联、分页和模糊查询、多个数据库)的更多相关文章

  1. iOS CoreData 增删改查详解

    最近在学习CoreData, 因为项目开发中需要,特意学习和整理了一下,整理出来方便以后使用和同行借鉴.目前开发使用的Swift语言开发的项目.所以整理出来的是Swift版本,OC我就放弃了. 虽然S ...

  2. IOS - CoreData 增删改查

    #pragma mark - Core Data Methods - (void)insertObjectWithFileName:(NSString *)fileName { /** SQL新增记录 ...

  3. Elasticsearch增删改查 之 —— mget多文档查询

    之前说过了针对单一文档的增删改查,基本也算是达到了一个基本数据库的功能.本篇主要描述的是多文档的查询,通过这个查询语法,可以根据多个文档的查询条件,返回多个文档集合. 更多内容可以参考我整理的ELK文 ...

  4. Java简单示例-用户登录、单个页面的增删改查及简单分页

    index.html  -登录->stulist.jsp (index.html传递到LoginServlet,进行登录检测及写入session,NO返回index.html界面,OK 跳转到s ...

  5. day38 mycql 初识概念,库(增删改查),表(增删改)以及表字段(增删改查),插入更新操作

    在Navicat中把已经生成的表逆向成模型 数据库上,右键-逆向数据库到模型 ego笔记: 增删改查 文件夹(库) 增 create database day43 charset utf8; 改 al ...

  6. SSH(Struts 2.3.31 + Spring 4.1.6 + Hibernate 5.0.12 + Ajax)框架整合实现简单的增删改查(包含分页,Ajax 无刷新验证该用户是否存在)

    软件152 余建强 该文将以员工.部门两表带领大家进入SSH的整合教程: 源码下载:http://download.csdn.net/detail/qq_35318576/9877235 SSH 整合 ...

  7. bootstrap-table 分页增删改查之一(分页)

    记录一下 bootstrap-table插件的使用 先看下效果图 首先是导入js <!--js jquery --> <script type="text/javascri ...

  8. iOS sqlite 增删改查 简单封装(基于 FMDB)

    /** *  对 sqlite 的使用进行简单封装,仅涉及简单的单表 增删改查 * *  基于 FMDB * *  操作基于 model ,数据库表字段与 model 属性一一对应,对 model 整 ...

  9. Oracle使用JDBC进行增删改查 表是否存在

    Oracle使用JDBC进行增删改查 数据库和表 table USERS (   USERNAME VARCHAR2(20) not null,   PASSWORD VARCHAR2(20) ) a ...

  10. MongoDB增删改查表文档

    MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写,是一个基于分布式文件存储的开源数据库系统.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介于关 ...

随机推荐

  1. Squirrel语言初探(可以使用VC6或者MinGW编译)

    Squirrel语言初探 为啥我要关注Squirrel语言?原来Squirrel就很像我希望设计出的理想中的语言(当然也不完全符合).比如我觉得Lua的语法表述不清晰,累赘,于是想用C系语法来代替Lu ...

  2. 实现IT服务弹性伸缩的利器

    随着互联网业务快速持续增长,IT资源使用量按需变化成为常态,这就要求信息部门能快速响应资源使用的变化要求,对运维提出不小挑战.比如电商.在线教育等企业经常推出一些秒杀.抢红包活动,在特定时间段对资源的 ...

  3. mysql int 整数类型 解释显示宽度 和 存储宽度

    存储宽度 是实际存储记录宽度 存储宽度默认是写死的,就算修改宽度也改变不了,改变的是显示宽度 ============有符号和无符号int============= 创建一个 无符号的 int 整数类 ...

  4. python第三方模块之paramiko模块

    目录: paramiko模块介绍 paramiko模块安装 paramiko模块使用 一.paramiko模块介绍 paramiko是一个用于做远程控制的模块,使用该模块可以对远程服务器进行命令或文件 ...

  5. Spark Streaming带状态更新

    带状态的更新是使用的updateStateByKey方法,里面传入一个函数,函数要自己写,注意需要设置checkpoint import org.apache.spark.streaming.kafk ...

  6. fold change的意义[转载]

    转自:https://zhidao.baidu.com/question/2052933434631672387.html 1.解释 解释:表达值倍数变化 ,分析,消除可能的混杂因素,必要时可以用读段 ...

  7. PAT 1105 Spiral Matrix[模拟][螺旋矩阵][难]

    1105 Spiral Matrix(25 分) This time your job is to fill a sequence of N positive integers into a spir ...

  8. ACM-ICPC 2017 Asia Shenyang Solution

    A: BBP Formula https://www.cnblogs.com/LzyRapx/p/7802790.html #include <bits/stdc++.h> using n ...

  9. Adobe AIR中使用Flex连接Sqlite数据库(1)(创建数据库和表,以及同步和异步执行模式)

    系列文章导航 Adobe AIR中使用Flex连接Sqlite数据库(1)(创建数据库和表) Adobe AIR中使用Flex连接Sqlite数据库(2)(添加,删除,修改以及语句参数) Adobe ...

  10. bzoj1619 / P2919 [USACO08NOV]守护农场Guarding the Farm

    P2919 [USACO08NOV]守护农场Guarding the Farm 相似题:P3456 [POI2007]GRZ-Ridges and Valleys 按海拔是否相同分块 每次bfs海拔相 ...