一、CoreData的简单使用

准备工作

  • 创建数据库

    1. 新建文件,选择CoreData -> DataModel
    2. 添加实体(表),Add Entity
    3. 给表中添加属性,点击Attributes下方的‘+’
  • 创建模型文件

    1. 新建文件,选择CoreData -> NSManaged Object subclass
    2. 根据提示,选择实体
  • 通过代码,关联数据库和实体

    - (void)viewDidLoad {[super viewDidLoad];/** 关联的时候,如果本地没有数据库文件,Coreadata自己会创建*/// 1. 上下文NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];// 2. 上下文关连数据库// 2.1 model模型文件NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];// 2.2 持久化存储调度器// 持久化,把数据保存到一个文件,而不是内存NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];// 2.3 设置CoreData数据库的名字和路径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:nil];context.persistentStoreCoordinator = store;_context = context;}

CoreData的基本操作(CURD)

  • 添加元素 - Create

    -(IBAction)addEmployee{// 创建一个员工对象 //Employee *emp = [[Employee alloc] init]; 不能用此方法创建Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];emp.name = @"wangwu";emp.height = @1.80;emp.birthday = [NSDate date];// 直接保存数据库NSError *error = nil;[_context save:&error];if (error) {NSLog(@"%@",error);}
    }
  • 读取数据 - Read

      -(IBAction)readEmployee{// 1.FetchRequest 获取请求对象NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];// 2.设置过滤条件// 查找zhangsanNSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"zhangsan"];request.predicate = pre;// 3.设置排序// 身高的升序排序NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];request.sortDescriptors = @[heigtSort];// 4.执行请求NSError *error = nil;NSArray *emps = [_context executeFetchRequest:request error:&error];if (error) {NSLog(@"error");}//NSLog(@"%@",emps);//遍历员工for (Employee *emp in emps) {NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday);}}
  • 修改数据 - Update

    -(IBAction)updateEmployee{// 改变zhangsan的身高为2m// 1.查找到zhangsan// 1.1FectchRequest 抓取请求对象NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];// 1.2设置过滤条件// 查找zhangsanNSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@", @"zhangsan"];request.predicate = pre;// 1.3执行请求NSArray *emps = [_context executeFetchRequest:request error:nil];// 2.更新身高for (Employee *e in emps) {e.height = @2.0;}// 3.保存NSError *error = nil;[_context save:&error];if (error) {NSLog(@"%@",error);}
    }
  • 删除数据 - Delete

    -(IBAction)deleteEmployee{// 删除 lisi// 1.查找lisi// 1.1FectchRequest 抓取请求对象NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];// 1.2设置过滤条件// 查找zhangsanNSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"lisi"];request.predicate = pre;// 1.3执行请求NSArray *emps = [_context executeFetchRequest:request error:nil];// 2.删除for (Employee *e in emps) {[_context deleteObject:e];}// 3.保存NSError *error = nil;[_context save:&error];if (error) {NSLog(@"%@",error);}}

二、CoreData的表关联

准备工作

  • 创建数据库

    1. 新建文件,选择CoreData -> DataModel
    2. 添加实体(表),Add Entity注意:这里根据关联添加多个实体
    3. 给表中添加属性,点击Attributes下方的‘+’
  • 创建模型文件

    1. 新建文件,选择CoreData -> NSManaged Object subclass
    2. 根据提示,选择实体,注意:这里先选择被关联的实体,最后添加最上层的实体
  • 通过代码,关联数据库和实体

    - (void)viewDidLoad {[super viewDidLoad];/** 关联的时候,如果本地没有数据库文件,Coreadata自己会创建*/// 1. 上下文NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];// 2. 上下文关连数据库// 2.1 model模型文件NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];// 2.2 持久化存储调度器// 持久化,把数据保存到一个文件,而不是内存NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];// 2.3 设置CoreData数据库的名字和路径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:nil];context.persistentStoreCoordinator = store;_context = context;}

基本操作

  • 添加元素 - Create

    -(IBAction)addEmployee{// 1. 创建两个部门 ios android//1.1 iOS部门Department *iosDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:_context];iosDepart.name = @"ios";iosDepart.departNo = @"0001";iosDepart.createDate = [NSDate date];//1.2 Android部门Department *andrDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:_context];andrDepart.name = @"android";andrDepart.departNo = @"0002";andrDepart.createDate = [NSDate date];//2. 创建两个员工对象 zhangsan属于ios部门 lisi属于android部门//2.1 zhangsanEmployee *zhangsan = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];zhangsan.name = @"zhangsan";zhangsan.height = @(1.90);zhangsan.birthday = [NSDate date];zhangsan.depart = iosDepart;//2.2 lisiEmployee *lisi = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];lisi.name = @"lisi";lisi.height = @2.0;lisi.birthday = [NSDate date];lisi.depart = andrDepart;//3. 保存数据库NSError *error = nil;[_context save:&error];if (error) {NSLog(@"%@",error);}
    }
  • 读取信息 - Read

    -(IBAction)readEmployee{// 读取ios部门的员工// 1.FectchRequest 抓取请求对象NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];// 2.设置过滤条件NSPredicate *pre = [NSPredicate predicateWithFormat:@"depart.name = %@",@"android"];request.predicate = pre;// 4.执行请求NSError *error = nil;NSArray *emps = [_context executeFetchRequest:request error:&error];if (error) {NSLog(@"error");}//遍历员工for (Employee *emp in emps) {NSLog(@"名字 %@ 部门 %@",emp.name,emp.depart.name);}
    }
  • 其他功能与前几种类似,这里不在赘述

三、CoreData的模糊查询

准备工作和上面类似,主要是查询方式不同

  • 模糊查询

    -(IBAction)readEmployee{// 1.FectchRequest 抓取请求对象NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];// 2.设置排序// 按照身高的升序排序NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];request.sortDescriptors = @[heigtSort];// 3.模糊查询// 3.1 名字以"wang"开头
    //    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name BEGINSWITH %@",@"wangwu1"];
    //    request.predicate = pre;// 名字以"1"结尾
    //    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name ENDSWITH %@",@"1"];
    //    request.predicate = pre;// 名字包含"wu1"
    //    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name CONTAINS %@",@"wu1"];
    //    request.predicate = pre;// like 匹配NSPredicate *pre = [NSPredicate predicateWithFormat:@"name like %@",@"*wu12"];request.predicate = pre;// 4.执行请求NSError *error = nil;NSArray *emps = [_context executeFetchRequest:request error:&error];if (error) {NSLog(@"error");}//遍历员工for (Employee *emp in emps) {NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday);}
    }
  • 分页查询

    -(void)pageSeacher{// 1. FectchRequest 抓取请求对象NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];// 2. 设置排序// 身高的升序排序NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];request.sortDescriptors = @[heigtSort];// 3. 分页查询// 总有共有15数据// 每次获取6条数据// 第一页 0,6// 第二页 6,6// 第三页 12,6 3条数据// 3.1 分页的起始索引request.fetchOffset = 12;// 3.2 分页的条数request.fetchLimit = 6;// 4. 执行请求NSError *error = nil;NSArray *emps = [_context executeFetchRequest:request error:&error];if (error) {NSLog(@"error");}// 5. 遍历员工for (Employee *emp in emps) {NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday);}
    }

四、多个数据库的使用

注意:

创建多个数据库,即创建多个DataModel
一个数据库对应一个上下文
需要根据bundle名创建上下文
添加或读取信息,需要根据不同的上下文,访问不同的实体

  • 关联数据库和实体

    - (void)viewDidLoad {[super viewDidLoad];// 一个数据库对应一个上下文_companyContext = [self setupContextWithModelName:@"Company"];_weiboContext = [self setupContextWithModelName:@"Weibo"];
    }        /**
    *  根据模型文件,返回一个上下文
    */
    -(NSManagedObjectContext *)setupContextWithModelName:(NSString *)modelName{// 1. 上下文NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];// 2. 上下文关连数据库// 2.1 model模型文件// 注意:如果使用下面的方法,如果 bundles为nil 会把bundles里面的所有模型文件的表放在一个数据库//NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];// 改为以下的方法获取:NSURL *companyURL = [[NSBundle mainBundle] URLForResource:modelName withExtension:@"momd"];NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:companyURL];// 2.2 持久化存储调度器// 持久化,把数据保存到一个文件,而不是内存NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];// 2.3 告诉Coredata数据库的名字和路径NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];NSString *sqliteName = [NSString stringWithFormat:@"%@.sqlite",modelName];NSString *sqlitePath = [doc stringByAppendingPathComponent:sqliteName];[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil];context.persistentStoreCoordinator = store;// 3. 返回上下文return context;
    }
  • 添加元素

    -(IBAction)addEmployee{// 1. 添加员工Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_companyContext];emp.name = @"zhagsan";emp.height = @2.3;emp.birthday = [NSDate date];// 直接保存数据库[_companyContext save:nil];// 2. 发微博Status *status =[NSEntityDescription insertNewObjectForEntityForName:@"Status" inManagedObjectContext:_weiboContext];status.text = @"发了一条微博!";status.createDate = [NSDate date];[_weiboContext save:nil];
    }

CoreData的简单使用相关推荐

  1. 让CoreData更简单些

    从简书迁移到掘金 前言 本文并不是CoreData从入门到精通之类的教程, 并不会涉及到过多的原理概念描述, 而是介绍如何让CoreData的使用变得更加简单明了, 方便亲民. 全文约六千字, 预计花 ...

  2. iOS开发 CoreData的简单使用

    CoreData介绍 CoreData是一门功能强大的数据持久化技术,位于SQLite数据库之上,它避免了SQL的复杂性,能让我们以更自然的方式与数据库进行交互.CoreData提供数据--OC对象映 ...

  3. IOS CoreData 简单使用CURD

    2019独角兽企业重金招聘Python工程师标准>>> iOS在CoreData中简单封装了SQLite,让开发者不需要写sql语句就可以使用SQLite进行CURD操作. 要使用C ...

  4. ios CoreData的使用(封装)

    本文讲解CoreData的使用,封装: 文章末尾附有demo 一.CoreData的简单理解 CoreData是一个模型层的技术,也是一种持久化技术,它能将模型对象的状态持久化到磁盘里,我们不需要使用 ...

  5. CoreData介绍

    http://blog.csdn.net/zh952016281/article/details/52105683 写在前面 在CoreData中有一些常用的类,称呼可能各不相同.所以这里先约定一些关 ...

  6. CoreData数据库

    了解CoreData CoreData是一个数据库,是对SQLite的封装.Xcode内部集成,coredata是orm.ORM(Object Relational Mapping)对象关系映射,or ...

  7. Realm在iOS中的简单使用

    一.Realm简单介绍 1.Realm简介 Realm是由美国YCombinator孵化的创业团队历时几年打造,第一个专门针对移动平台设计的数据库 Realm是一个跨平台的移动数据库引擎,目前支持iO ...

  8. iOS中几种数据持久化方案总结

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

  9. iOS realm

    文章目录 简介 Realm的优势与亮点 Realm Browser Realm中的一些重要概念 Realm的安装-CocoaPods Xcode插件 常用属性和方法 Realm的类定义说明 RLMRe ...

最新文章

  1. SimpleAdapter真不简单!
  2. leetcode 925. 长按键入
  3. hadoop 单节点安装
  4. Swagger2的使用
  5. 【架构师】【数据库基础】【笔记 01】快速了解数据库系统的重要概念01
  6. java实现同步的两种方式
  7. 删除 java代码中所有的注释
  8. Python Cookbook by Eric
  9. hinkPad T510系列主要机型对比
  10. javplayer 使用教程_Revit形状编辑操作大全(文末附39套BIM软件自学教程)
  11. 自己收集的全国行政区划,具体到县级,不包括过直辖市和特别行政区
  12. QChartView绘制可缩放和平移的图表QChart(此例子为折线图)
  13. python实现文件重命名_python实现文件重命名
  14. 数据库迁移工具Kettle连接Mysql数据库报错:Driver class ‘org.gjt.mm.mysql.Driver‘ could not be found, make sure the解决
  15. 按钮如何控制tab页面跳转
  16. 电脑报价管理系统C语言,C语言笔记本电脑销售系统课设(附源码).doc
  17. buuctf web1
  18. VLAN的原理及配置
  19. 基于SpringBoot的健身房管理系统
  20. 智能科学与技术与数据科学与大数据技术哪个好

热门文章

  1. 生物信息9天速成班—成为团队中不可或缺的人
  2. R语言聚类分析之基于划分的聚类KMeans实战:基于葡萄酒数据
  3. R语言使用ggpubr包的ggarrange函数组合多张结论图:使用ggpubr包在散点图的侧面添加辅助图形、并使用NULL将不需要可视化的侧面留白
  4. R使用LSTM模型构建深度学习文本分类模型(Quora Insincere Questions Classification)
  5. R可视化绘制指数分布(Exponential Distribution)
  6. 扩展卡尔曼滤波EKF与多传感器融合
  7. STAR: ultrafast universal RNA-seq aligner STAR:超快的通用RNA-seq比对器
  8. java编程100题
  9. mybatis 同名方法_MyBatis(四):xml配置详解
  10. skycons.js 基于canvas的天气动态js插件