IOS-CoreData(增删改查、表关联、分页和模糊查询、多个数据库)
1>什么是CoreData
一、CoreData基本使用-增删改查和表关联
- //
- // ViewController.m
- // IOS_0121_CoreData
- //
- // Created by ma c on 16/1/21.
- // Copyright © 2016年 博文科技. All rights reserved.
- //
- #import "ViewController.h"
- #import <CoreData/CoreData.h>
- #import "Employee.h"
- #import "Department.h"
- @interface ViewController ()
- @property (nonatomic, strong) NSManagedObjectContext *context;
- @end
- @implementation ViewController
- - (void)viewDidLoad {
- [super viewDidLoad];
- //1.创建模型文件(相当于数据库中的表)
- //2.添加实体(一张表)
- //3.创建实体类(相当于模型)
- //4.生成上下文,关联模型文件生成数据库
- //上下文
- self.context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
- //模型数据文件
- NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
- //持久化存储器
- //把数据保存到一个文件,而不是内存
- NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
- //数据名字和路径
- NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
- NSString *sqlitePath = [path stringByAppendingPathComponent:@"company.sqlite"];
- NSLog(@"%@",sqlitePath);
- NSURL *url = [NSURL fileURLWithPath:sqlitePath];
- [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:nil];
- self.context.persistentStoreCoordinator = store;
- }
- //数据库操作ADUQ (ADD、Delete、Update、Query)
- #pragma mark - 添加员工
- - (IBAction)addEmployee
- {
- Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];
- emp.name = @"bowen";
- emp.height = @"";
- emp.birthday = [NSDate date];
- //直接保存
- NSError *error = nil;
- [self.context save:&error];
- if (error) {
- NSLog(@"%@",error);
- }
- }
- #pragma mark - 查询员工
- - (IBAction)searchEmployee
- {
- //1.NSFetchRequest 抓取请求对象
- NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
- //2.设置过滤条件
- NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"bowen"];
- request.predicate = pre;
- //3.排序
- NSSortDescriptor *heightSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:YES];
- request.sortDescriptors = @[heightSort];
- //4.执行请求
- NSError *error = nil;
- NSArray *emps = [self.context executeFetchRequest:request error:&error];
- if (error) {
- NSLog(@"%@",error);
- }
- for (Employee *emp in emps) {
- NSLog(@"name:%@ height:%@ birthday:%@",emp.name, emp.height, emp.birthday);
- }
- }
- #pragma mark - 更新员工
- - (IBAction)updateEmployee
- {
- //1.查找
- //获取对象
- NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
- //设置过滤条件
- NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"bowen"];
- request.predicate = pre;
- //执行请求
- NSArray *emps = [self.context executeFetchRequest:request error:nil];
- //2.更新
- for (Employee *emp in emps) {
- emp.height = @"";
- }
- //3.保存
- [self.context save:nil];
- }
- #pragma mark - 删除员工
- - (IBAction)deleteEmployee
- {
- //1.查找
- //获取对象
- NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
- //设置过滤条件
- NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"bowen"];
- request.predicate = pre;
- //执行请求
- NSArray *emps = [self.context executeFetchRequest:request error:nil];
- //2.删除
- for (Employee *emp in emps) {
- [self.context deleteObject:emp];
- }
- //3.保存
- [self.context save:nil];
- }
- #pragma mark - 表关联
- - (IBAction)AddRelationship
- {
- //创建两个部门:IOS、Android
- Department *IOSDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:self.context];
- IOSDepart.departNo = @"";
- IOSDepart.name = @"IOS";
- IOSDepart.createDate = [NSDate date];
- Department *AndroidDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:self.context];
- AndroidDepart.departNo = @"";
- AndroidDepart.name = @"Android";
- AndroidDepart.createDate = [NSDate date];
- //创建两个员工:bowen1,bowen2
- Employee *emp1 = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];
- emp1.name = @"bowen1";
- emp1.height = @"";
- emp1.birthday = [NSDate date];
- emp1.depart = IOSDepart;
- Employee *emp2 = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];
- emp2.name = @"bowen2";
- emp2.height = @"";
- emp2.birthday = [NSDate date];
- emp2.depart = AndroidDepart;
- //保存
- [self.context save:nil];
- }
- - (IBAction)searchRelationship
- {
- //读取IOS部门员工
- //1.NSFetchRequest 抓取请求对象
- NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
- //2.设置过滤条件
- NSPredicate *pre = [NSPredicate predicateWithFormat:@"depart.name = %@",@"IOS"];
- request.predicate = pre;
- //3.执行请求
- NSError *error = nil;
- NSArray *emps = [self.context executeFetchRequest:request error:&error];
- if (error) {
- NSLog(@"%@",error);
- }
- for (Employee *emp in emps) {
- NSLog(@"name:%@ height:%@ birthday:%@",emp.name, emp.height, emp.birthday);
- }
- }
- - (void)didReceiveMemoryWarning {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- @end
三、分页查询和模糊查询
- //
- // ViewController.m
- // IOS_0121_CoreData
- //
- // Created by ma c on 16/1/21.
- // Copyright © 2016年 博文科技. All rights reserved.
- //
- #import "ViewController.h"
- #import <CoreData/CoreData.h>
- #import "Employee.h"
- #import "Department.h"
- @interface ViewController ()
- @property (nonatomic, strong) NSManagedObjectContext *context;
- @end
- @implementation ViewController
- - (void)viewDidLoad {
- [super viewDidLoad];
- //1.创建模型文件(相当于数据库中的表)
- //2.添加实体(一张表)
- //3.创建实体类(相当于模型)
- //4.生成上下文,关联模型文件生成数据库
- //上下文
- self.context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
- //模型数据文件
- NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
- //持久化存储器
- //把数据保存到一个文件,而不是内存
- NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
- //数据名字和路径
- NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
- NSString *sqlitePath = [path stringByAppendingPathComponent:@"company.sqlite"];
- NSLog(@"%@",sqlitePath);
- NSURL *url = [NSURL fileURLWithPath:sqlitePath];
- [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:nil];
- self.context.persistentStoreCoordinator = store;
- }
- //数据库操作ADUQ (ADD、Delete、Update、Query)
- #pragma mark - 添加员工
- - (IBAction)addEmployee
- {
- for (int i = ; i < ; i++) {
- Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];
- emp.name = [NSString stringWithFormat:@"bowen%d",i];
- emp.height = [NSString stringWithFormat:@"%d",+i];
- emp.birthday = [NSDate date];
- }
- //直接保存
- NSError *error = nil;
- [self.context save:&error];
- if (error) {
- NSLog(@"%@",error);
- }
- }
- #pragma mark - 分页查询
- - (IBAction)pagingAndQuerying
- {
- //1.NSFetchRequest 抓取请求对象
- NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
- //2.排序
- NSSortDescriptor *heightSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:YES];
- request.sortDescriptors = @[heightSort];
- //3.分页查询
- //分页的起始索引
- request.fetchOffset = ;
- //分页的条数
- request.fetchLimit = ;
- //4.执行请求
- NSError *error = nil;
- NSArray *emps = [self.context executeFetchRequest:request error:&error];
- if (error) {
- NSLog(@"%@",error);
- }
- for (Employee *emp in emps) {
- NSLog(@"name:%@ height:%@ birthday:%@",emp.name, emp.height, emp.birthday);
- }
- }
- - (IBAction)fuzzyQuery
- {
- //1.NSFetchRequest 抓取请求对象
- NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
- //2.排序
- NSSortDescriptor *heightSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:YES];
- request.sortDescriptors = @[heightSort];
- //3.模糊查询
- //名字以“bowen1”开头
- //NSPredicate *pre = [NSPredicate predicateWithFormat:@"name BEGINSWITH %@",@"bowen1"];
- //request.predicate = pre;
- //名字以“1”结尾
- //NSPredicate *pre = [NSPredicate predicateWithFormat:@"name ENDSWITH %@",@"1"];
- //request.predicate = pre;
- //名字包含“wen1”结尾
- //NSPredicate *pre = [NSPredicate predicateWithFormat:@"name CONTAINS %@",@"1"];
- //request.predicate = pre;
- //like
- //名字以“1”结尾
- //NSPredicate *pre = [NSPredicate predicateWithFormat:@"name like %@",@"*wen14"];
- //request.predicate = pre;
- //名字以“bowen2”开头
- NSPredicate *pre = [NSPredicate predicateWithFormat:@"name like %@",@"bowen2*"];
- request.predicate = pre;
- //4.执行请求
- NSError *error = nil;
- NSArray *emps = [self.context executeFetchRequest:request error:&error];
- if (error) {
- NSLog(@"%@",error);
- }
- for (Employee *emp in emps) {
- NSLog(@"name:%@ height:%@ birthday:%@",emp.name, emp.height, emp.birthday);
- }
- }
- @end
三、创建多个数据库
- //
- // ViewController.m
- // IOS_0121_CoreData
- //
- // Created by ma c on 16/1/21.
- // Copyright © 2016年 博文科技. All rights reserved.
- //
- #import "ViewController.h"
- #import <CoreData/CoreData.h>
- #import "Employee.h"
- #import "Status.h"
- @interface ViewController ()
- @property (nonatomic, strong) NSManagedObjectContext *companyContext;
- @property (nonatomic, strong) NSManagedObjectContext *weibocontext;
- @end
- @implementation ViewController
- - (void)viewDidLoad {
- [super viewDidLoad];
- //一个数据库对应着一个上下文
- self.companyContext = [self setupContextWithModelName:@"Company"];
- self.weibocontext = [self setupContextWithModelName:@"weibo"];
- }
- //根据模型文件返回上下文
- - (NSManagedObjectContext *)setupContextWithModelName:(NSString *)modelName
- {
- //1.创建模型文件(相当于数据库中的表)
- //2.添加实体(一张表)
- //3.创建实体类(相当于模型)
- //4.生成上下文,关联模型文件生成数据库
- //上下文
- NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
- //模型数据文件
- //使用下面的方法,如果boundles为空,会把boundles里面所有的模型文件的表都放在一个数据库中
- //NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
- NSLog(@"%@",[[NSBundle mainBundle] bundlePath]);
- NSURL *modelURL = [[NSBundle mainBundle] URLForResource:modelName withExtension:@"momd"];
- NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
- //持久化存储器
- //把数据保存到一个文件,而不是内存
- NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
- //数据名字和路径
- NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
- NSString *sqlliteName = [NSString stringWithFormat:@"%@.sqllite",modelName];
- NSString *sqlitePath = [path stringByAppendingPathComponent:sqlliteName];
- NSLog(@"%@",sqlitePath);
- NSURL *url = [NSURL fileURLWithPath:sqlitePath];
- [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:nil];
- context.persistentStoreCoordinator = store;
- return context;
- }
- //数据库操作ADUQ (ADD、Delete、Update、Query)
- #pragma mark - 添加
- - (IBAction)add
- {
- Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.companyContext];
- emp.name = @"bowen";
- emp.height = @"";
- emp.birthday = [NSDate date];
- Status *status = [NSEntityDescription insertNewObjectForEntityForName:@"Status" inManagedObjectContext:self.weibocontext];
- status.text = @"回家";
- status.createDate = @"2015-01-28";
- [self.companyContext save:nil];
- [self.weibocontext save:nil];
- }
- #pragma mark - 查询
- - (IBAction)querying
- {
- }
- @end
IOS-CoreData(增删改查、表关联、分页和模糊查询、多个数据库)的更多相关文章
- iOS CoreData 增删改查详解
最近在学习CoreData, 因为项目开发中需要,特意学习和整理了一下,整理出来方便以后使用和同行借鉴.目前开发使用的Swift语言开发的项目.所以整理出来的是Swift版本,OC我就放弃了. 虽然S ...
- IOS - CoreData 增删改查
#pragma mark - Core Data Methods - (void)insertObjectWithFileName:(NSString *)fileName { /** SQL新增记录 ...
- Elasticsearch增删改查 之 —— mget多文档查询
之前说过了针对单一文档的增删改查,基本也算是达到了一个基本数据库的功能.本篇主要描述的是多文档的查询,通过这个查询语法,可以根据多个文档的查询条件,返回多个文档集合. 更多内容可以参考我整理的ELK文 ...
- Java简单示例-用户登录、单个页面的增删改查及简单分页
index.html -登录->stulist.jsp (index.html传递到LoginServlet,进行登录检测及写入session,NO返回index.html界面,OK 跳转到s ...
- day38 mycql 初识概念,库(增删改查),表(增删改)以及表字段(增删改查),插入更新操作
在Navicat中把已经生成的表逆向成模型 数据库上,右键-逆向数据库到模型 ego笔记: 增删改查 文件夹(库) 增 create database day43 charset utf8; 改 al ...
- 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 整合 ...
- bootstrap-table 分页增删改查之一(分页)
记录一下 bootstrap-table插件的使用 先看下效果图 首先是导入js <!--js jquery --> <script type="text/javascri ...
- iOS sqlite 增删改查 简单封装(基于 FMDB)
/** * 对 sqlite 的使用进行简单封装,仅涉及简单的单表 增删改查 * * 基于 FMDB * * 操作基于 model ,数据库表字段与 model 属性一一对应,对 model 整 ...
- Oracle使用JDBC进行增删改查 表是否存在
Oracle使用JDBC进行增删改查 数据库和表 table USERS ( USERNAME VARCHAR2(20) not null, PASSWORD VARCHAR2(20) ) a ...
- MongoDB增删改查表文档
MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写,是一个基于分布式文件存储的开源数据库系统.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介于关 ...
随机推荐
- Squirrel语言初探(可以使用VC6或者MinGW编译)
Squirrel语言初探 为啥我要关注Squirrel语言?原来Squirrel就很像我希望设计出的理想中的语言(当然也不完全符合).比如我觉得Lua的语法表述不清晰,累赘,于是想用C系语法来代替Lu ...
- 实现IT服务弹性伸缩的利器
随着互联网业务快速持续增长,IT资源使用量按需变化成为常态,这就要求信息部门能快速响应资源使用的变化要求,对运维提出不小挑战.比如电商.在线教育等企业经常推出一些秒杀.抢红包活动,在特定时间段对资源的 ...
- mysql int 整数类型 解释显示宽度 和 存储宽度
存储宽度 是实际存储记录宽度 存储宽度默认是写死的,就算修改宽度也改变不了,改变的是显示宽度 ============有符号和无符号int============= 创建一个 无符号的 int 整数类 ...
- python第三方模块之paramiko模块
目录: paramiko模块介绍 paramiko模块安装 paramiko模块使用 一.paramiko模块介绍 paramiko是一个用于做远程控制的模块,使用该模块可以对远程服务器进行命令或文件 ...
- Spark Streaming带状态更新
带状态的更新是使用的updateStateByKey方法,里面传入一个函数,函数要自己写,注意需要设置checkpoint import org.apache.spark.streaming.kafk ...
- fold change的意义[转载]
转自:https://zhidao.baidu.com/question/2052933434631672387.html 1.解释 解释:表达值倍数变化 ,分析,消除可能的混杂因素,必要时可以用读段 ...
- PAT 1105 Spiral Matrix[模拟][螺旋矩阵][难]
1105 Spiral Matrix(25 分) This time your job is to fill a sequence of N positive integers into a spir ...
- ACM-ICPC 2017 Asia Shenyang Solution
A: BBP Formula https://www.cnblogs.com/LzyRapx/p/7802790.html #include <bits/stdc++.h> using n ...
- Adobe AIR中使用Flex连接Sqlite数据库(1)(创建数据库和表,以及同步和异步执行模式)
系列文章导航 Adobe AIR中使用Flex连接Sqlite数据库(1)(创建数据库和表) Adobe AIR中使用Flex连接Sqlite数据库(2)(添加,删除,修改以及语句参数) Adobe ...
- bzoj1619 / P2919 [USACO08NOV]守护农场Guarding the Farm
P2919 [USACO08NOV]守护农场Guarding the Farm 相似题:P3456 [POI2007]GRZ-Ridges and Valleys 按海拔是否相同分块 每次bfs海拔相 ...