CoreData学习笔记(1)

CoreData的简单使用sql

 

一.单表简单操做数据库

1.建立模型文件 [至关于一个数据库里的表]app

    2.添加实体 [一张表]fetch

    3.建立实体类 [至关模型]spa

    4.生成上下文 关联模型文件生成数据库orm

    /*sqlite

     * 关联的时候,若是本地没有数据库文件,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;

 

5.对数据作增删查改操做

A.添加员工

-(void)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 读取员工

-(void)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 更新员工

-(void)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 删除员工

-(void)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];

 

}

二.多表关联查询和操做

//

//  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];

    for (int i = 0; i < 15; i++) {

        Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];

        emp.name = [NSString stringWithFormat:@"wangwu%d",i];

        emp.height = @(1.80 + i);

        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"];

    // 3.设置排序

    // 身高的升序排序

    NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];

    request.sortDescriptors = @[heigtSort];

    // 模糊查询

    // 名字以"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

    //以wangwu1*开头

    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");

    }

    //NSLog(@"%@",emps);

    //遍历员工

    for (Employee *emp in emps) {

        NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday);

    }  

}

#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 = 12;

    // 分页的条数

    request.fetchLimit = 6;

    // 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);

    }

}

@end

三.多个数据库的查询

#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

相关文章
相关标签/搜索