(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

IOS CoreData的(增删查改)的更多相关文章

  1. 分享一段ios数据库代码,包括对表的创建、升级、增删查改

    分享一段ios数据库代码.包括创建.升级.增删查改. 里面的那些类不必细究,主要是数据库的代码100%可用. 数据库升级部分,使用switch,没有break,低版本一次向高版本修改. // DB.h ...

  2. 6.在MVC中使用泛型仓储模式和依赖注入实现增删查改

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pat ...

  3. 3.EF 6.0 Code-First实现增删查改

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-entity-framework-5-0-code- ...

  4. 4.在MVC中使用仓储模式进行增删查改

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-using-the-repository-pattern-in-mvc/ 系列目录: ...

  5. 5.在MVC中使用泛型仓储模式和工作单元来进行增删查改

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pat ...

  6. jdbc的实例应用:增删查改实现

    //在jdbc中进行增删查改 //查看所有 public static void findAll() { String url = "jdbc:mysql://localhost:3306/ ...

  7. 用javascript实现html元素的增删查改[xyytit]

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  8. hibernate基础增删查改简单实例

    hibernate 基础理论知识网上很多,可以百度和google.这里不做多的介绍,以一个User表来开展例子 建一个web-project 我这里用了junit单元测试环境来进行增删查改的测试,别的 ...

  9. Entity FrameWork 增删查改的本质

    之前的文章里面已经说了,EF的增删查改.那时候的修改,删除,只能是先查询出来要修改的数据,再修改,删除...现在来一个改进版的,增删查改. 1.Add static void Add() { //1. ...

随机推荐

  1. .net: 泛型List<T> 轉換成 DataTable類型

    public static DataTable ListToDataTable<T>(List<T> entitys) { //检查实体集合不能为空 ) { return ne ...

  2. Flask中的的SQLAlchemy

    好久没有更新Blog了 今天来聊一聊 Python 的 ORM 框架 SQLAlchemy 有的孩子已经听说过这个框架的大名了,也听说了 SQLAlchemy 没有 Django 的 Models 好 ...

  3. (转) 来自: http://man.linuxde.net/tee

    tee命令文件过滤分割与合并 tee命令用于将数据重定向到文件,另一方面还可以提供一份重定向数据的副本作为后续命令的stdin.简单的说就是把数据重定向到给定文件和屏幕上. 存在缓存机制,每1024个 ...

  4. 解决dns服务器未找到问题 &&DNS解析服务器&&连接问题

    第一部分: 有时已经连接到了网络,但是却提示未找到dns服务器,或未连接dns服务器,这多是因为dns设置的问题.下面是几种可行的解决方法. 方法一: 1. win + R   -> cmd - ...

  5. 第十九章:UTC time和local time的互换

    通常我们服务器端的时间使用UTC格式,避免服务器的时区对最终的时间产生影响.而客户端需要根据具体的时区显示local time,本文将介绍如何将服务器的UTC time(基于asp.net web a ...

  6. VS中为什么不同的项目类型属性查看和设置的界面不一样

    在VS中,存在ATL.MFC.Win32.CLR.常规等等各种工程模板,这些工程模板对应于开发不同类型的应用,比如要开发com,你应该选ATL:开发最原始的通过API代用操作系统的应用,应该用Win3 ...

  7. Windows的加密能力

    尽管Windows不再具备往日那样的统治地位,在智能手机领域,甚至已经沦落为一种小众平台,Windows仍然是主要的商业应用运行平台.软件开发平台.硬件及结构等设计软件运行平台.大多数人在学习计算机时 ...

  8. NBUT 1107——盒子游戏——————【博弈类】

    盒子游戏 Time Limit:1000MS     Memory Limit:65535KB     64bit IO Format: Submit Status Practice NBUT 110 ...

  9. JS之this那些事

    一直以来,对this的讨论都是热门话题.有人说掌握了this就掌握了JavaScript的80%,说法有点夸张,但可见this的重要性.至今记录了很多关于this的零碎笔记,今天就来个小结. 本人看过 ...

  10. java.lang.Exception: DEBUG -- CLOSE BY CLIENT STACK TRACE 的理解

    [2013-12-06 11:06:21,715] [C3P0PooledConnectionPoolManager[identityToken->2tl0n98y1iwg7cbdzzq7a|7 ...