IOS CoreData的(增删查改)

时间:2023-12-09 13:33:07

(1).CoreData
a>什么是CoreData
b>CoreData增删改查

"什么时候使用COredata 什么时候使用FMDatabases"
CoreData 在公司使用的比较少,用户的比较多的是FMDatabases

数据存储的结构比较简单的时候,使用CoreData

开发效率会高点,为什么?面向对象,而且不用写sql语句
FMDatabases 数据结果比较复杂的时候,表与表之前的关联比较的时候

CoreData表与表之前的关联

查询
分页查询
模糊查询

一个数据库有一个模型文件对应
两个数据库有两个模型文件对应

CoreData 其实底层也是要写sql 语句
CoreData 帮我们把sql语句封装

到底使用CoreData的效率高还是直接使用sql代码的运行效率、

一、CoreData的简单使用
1.什么是CoreData
2.CoreData的使用步骤
3.创建公司模型文件并创建员工实体Employee(name,age,height)
4.创建上下文关联数据库文件
5.保存员工数据
6.读取员工数据
[_context executeFetchRequest:request error:&error];
*> 读取所有员工
*> 读取张三的员工信息
NSPredicate: @"name = %@",@"zhangsan"
*> 身高排序

6.修改员工数据
*> 修改张三的身高
[_context save]

7.删除员工数据
[_context deleteObject:emp]

二、高级查询
//c表示不区分大小写
// like '*jp'"   //以jp结束
//@"name BEGINSWITH[cd] '李'" //姓李的员工
//@"name ENDSWITH[c] '梦'"   //以梦结束的员工
//@"name CONTAINS[d] '宗'"   //包含有"宗"字的员工
//分页fetchOffset fetchBatchSize

三、查找多表关联
1> 添加部门表,查询属于某个部门的员工

四、多个model文件,多个context;

NSBundle *bundle = [NSBundle mainBundle];

NSString *momPath = [bundle pathForResource:@"Model" ofType:@"momd”];
                     
NSManagedObjectModel *model = [[NSManagedObjectModel alloc]initWithContentsOfURL:[NSURL fileURLWithPath:modelPath]];

五、开打SQLITE开关

CoreData的基本使用(增删查改)

//
// ViewController.m
// 01.CoreData的简单使用
//
// Created by apple on 14/12/5.
// Copyright (c) 2014年 heima. All rights reserved.
// #import "ViewController.h"
#import <CoreData/CoreData.h> #import "Employee.h" @interface ViewController (){
NSManagedObjectContext *_context;
} @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib. // 1.创建模型文件 [相当于一个数据库里的表]
// 2.添加实体 [一张表]
// 3.创建实体类 [相当模型]
// 4.生成上下文 关联模型文件生成数据库
/*
* 关联的时候,如果本地没有数据库文件,Coreadata自己会创建
*/ // 上下文
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init]; // 上下文关连数据库 // model模型文件
NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil]; // 持久化存储调度器
// 持久化,把数据保存到一个文件,而不是内存
NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; // 告诉Coredata数据库的名字和路径
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"];
NSLog(@"%@",sqlitePath);
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil]; context.persistentStoreCoordinator = store;
_context = context; } // 数据库的操作 CURD Create Update Read Delete
#pragma mark 添加员工
-(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);
}
} #pragma mark 读取员工
-(IBAction)readEmployee{ // 1.FectchRequest 抓取请求对象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 2.设置过滤条件
// 查找zhangsan
NSPredicate *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);
} } #pragma mark 更新员工
-(IBAction)updateEmployee{
// 改变zhangsan的身高为2m // 1.查找到zhangsan
// 1.1FectchRequest 抓取请求对象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 1.2设置过滤条件
// 查找zhangsan
NSPredicate *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.保存
[_context save:nil];
} #pragma mark 删除员工
-(IBAction)deleteEmployee{ // 删除 lisi // 1.查找lisi
// 1.1FectchRequest 抓取请求对象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 1.2设置过滤条件
// 查找zhangsan
NSPredicate *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.保存
[_context save:nil]; }
@end

CoreData表之前的关联

1.创建模型文件 [相当于一个数据库里的表]
    2.添加实体 [一张表]
    3.创建实体类 [相当模型]
    4.生成上下文 关联模型文件生成数据库
    /*
     * 关联的时候,如果本地没有数据库文件,Coreadata自己会创建
     */

#import "ViewController.h"
#import <CoreData/CoreData.h> #import "Employee.h"
#import "Department.h" @interface ViewController (){
NSManagedObjectContext *_context;
} @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib. // 1.创建模型文件 [相当于一个数据库里的表]
// 2.添加实体 [一张表]
// 3.创建实体类 [相当模型]
// 4.生成上下文 关联模型文件生成数据库
/*
* 关联的时候,如果本地没有数据库文件,Coreadata自己会创建
*/ // 上下文
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init]; // 上下文关连数据库 // model模型文件
NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil]; // 持久化存储调度器
// 持久化,把数据保存到一个文件,而不是内存
NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; // 告诉Coredata数据库的名字和路径
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"];
NSLog(@"%@",sqlitePath);
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil]; context.persistentStoreCoordinator = store;
_context = context; } // 数据库的操作 CURD Create Update Read Delete
#pragma mark 添加员工
-(IBAction)addEmployee{ // 创建两个部门 ios android
Department *iosDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:_context];
iosDepart.name = @"ios";
iosDepart.departNo = @"";
iosDepart.createDate = [NSDate date]; Department *andrDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:_context];
andrDepart.name = @"android";
andrDepart.departNo = @"";
andrDepart.createDate = [NSDate date]; // 创建两个员工对象 zhangsan属于ios部门 lisi属于android部门
Employee *zhangsan = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];
zhangsan.name = @"zhangsan";
zhangsan.height = @(1.90);
zhangsan.birthday = [NSDate date];
zhangsan.depart = iosDepart; Employee *lisi = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context]; lisi.name = @"lisi";
lisi.height = @2.0;
lisi.birthday = [NSDate date];
lisi.depart = andrDepart; // 直接保存数据库
NSError *error = nil;
[_context save:&error]; if (error) {
NSLog(@"%@",error);
}
} #pragma mark 读取员工
-(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");
} //NSLog(@"%@",emps);
//遍历员工
for (Employee *emp in emps) {
NSLog(@"名字 %@ 部门 %@",emp.name,emp.depart.name);
} } #pragma mark 更新员工
-(IBAction)updateEmployee{ } #pragma mark 删除员工
-(IBAction)deleteEmployee{ }
@end

CoreData分页查询

#pragma mark 分页查询
-(void)pageSeacher{
// 1.FectchRequest 抓取请求对象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 3.设置排序
// 身高的升序排序
NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
request.sortDescriptors = @[heigtSort]; // 总有共有15数据
// 每次获取6条数据
// 第一页 0,6
// 第二页 6,6
// 第三页 12,6 3条数据
// 分页查询 limit 0,5 // 分页的起始索引
request.fetchOffset = ; // 分页的条数
request.fetchLimit = ; // 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);
} }

CoreData的多个数据库

#import "ViewController.h"
#import <CoreData/CoreData.h> #import "Employee.h"
#import "Status.h" @interface ViewController (){
NSManagedObjectContext *_context;
NSManagedObjectContext *_companyContext;
NSManagedObjectContext *_weiboContext;
} @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib. // 一个数据库对应一个上下文
_companyContext = [self setupContextWithModelName:@"Company"];
_weiboContext = [self setupContextWithModelName:@"Weibo"]; //_context = context; } /**
* 根据模型文件,返回一个上下文
*/
-(NSManagedObjectContext *)setupContextWithModelName:(NSString *)modelName{ // 1.创建模型文件 [相当于一个数据库里的表]
// 2.添加实体 [一张表]
// 3.创建实体类 [相当模型]
// 4.生成上下文 关联模型文件生成数据库
/*
* 关联的时候,如果本地没有数据库文件,Coreadata自己会创建
*/ // 上下文
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init]; // 上下文关连数据库 // model模型文件 // 使用下面的方法,如果 bundles为nil 会把bundles里面的所有模型文件的表放在一个数据库
//NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
NSLog(@"%@",[[NSBundle mainBundle] bundlePath]); NSURL *companyURL = [[NSBundle mainBundle] URLForResource:modelName withExtension:@"momd"];
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:companyURL]; // 持久化存储调度器
// 持久化,把数据保存到一个文件,而不是内存
NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; // 告诉Coredata数据库的名字和路径
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *sqliteName = [NSString stringWithFormat:@"%@.sqlite",modelName];
NSString *sqlitePath = [doc stringByAppendingPathComponent:sqliteName];
NSLog(@"%@",sqlitePath);
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil]; context.persistentStoreCoordinator = store; return context;
} // 数据库的操作 CURD Create Update Read Delete
#pragma mark 添加员工
-(IBAction)addEmployee{
// 添加员工
Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_companyContext];
emp.name = @"zhagsan";
emp.height = @2.3;
emp.birthday = [NSDate date]; // 直接保存数据库
NSError *error = nil;
[_companyContext save:&error]; if (error) {
NSLog(@"%@",error);
} // 发微博
Status *status =[NSEntityDescription insertNewObjectForEntityForName:@"Status" inManagedObjectContext:_weiboContext]; status.text = @"毕业,挺激动";
status.createDate = [NSDate date]; [_weiboContext save:nil];
} #pragma mark 读取员工
-(IBAction)readEmployee{ NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 4.执行请求
NSError *error = nil; NSArray *emps = [_companyContext executeFetchRequest:request error:&error];
if (error) {
NSLog(@"error");
} //NSLog(@"%@",emps);
//遍历员工
for (Employee *emp in emps) {
NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday);
} } @end