zoukankan      html  css  js  c++  java
  • CoreDate的使用

    使用步骤:

    1.创建模型文件---相当于数据库里的一个表

    a.创建文件Core Data -->Data Model

    2.添加实体

    a.在模型文件中点加号Add Entity创建实体

    b.添加属性

    3.创建实体类(相当模型)

    a.创建文件Core Data -->NSManagedObject subslass 并关联刚才的模型文件中的表

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

    a.在控制器文件.m中添加框架 #import<CoreData/CoreData.h>

    b.@interface ViewController (){
        NSManagedObjectContext *_context;
    }

    声明上下文 NSManagedObjectContext  *context = [[NSManagedObjectContext   alloc] init];

    c.声明model模型文件 NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];//如果bundles为空,会自动关联Bundles里面的所有模型文件的表放在一个数据库里面

    d.声明持久化存储调度器 NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];//持久化,把数据保存到一个文件,而不是内存。

    e.告诉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];

    g.设置持久化

       context.persistentStoreCoordinator = store;
        _context = context;

    5.保存对象到数据库

    a.声明实体类Employee

    b.创建一个实体对象     Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];

    c.设置实体属性

    d.直接保存数据库 [_context save:nil];

     

    6.从数据库获取对象

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

    7.更新数据

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

    8.删除数据

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

     9.分页查询
    #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);
        }
        
    }
     
    10、模糊查询
    在查询数据的代码中加入条件
    // 模糊查询
        // 名字以"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;
     
     
    11.多个数据库关联
    //a.一个数据库对应一个上下文
     
    @interface ViewController (){
        NSManagedObjectContext *_context;
        NSManagedObjectContext *_companyContext;
        NSManagedObjectContext *_weiboContext;
    }
     
        _companyContext = [self setupContextWithModelName:@"Company"];
        _weiboContext = [self setupContextWithModelName:@"Weibo"];
     
    -(NSManagedObjectContext *)setupContextWithModelName:(NSString *)modelName{
        
      
        
        // 上下文
        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;
    }
     
    b.输入数据
        // 添加员工
        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];
     
     
    12.打开CoreData的SQL语句输出开关
    a.打开Product,点击EditScheme。。
    b.点击Arguments,在ArgumentsPassed On Launch 中添加2项。
      1》-com.apple.CoreData.SQLDebug
      2》1     //1要在上
     
     
     
     
     
     
  • 相关阅读:
    js验证邮箱
    输出一个金字塔
    仿QQ聊天软件2.0版
    zoj 3662 第37届ACM/ICPC长春赛区H题(DP)
    zoj 3659 第37届ACM/ICPC 长春赛区现场赛E题 (并查集)
    zoj 3640 概率dp
    hdu 5203 && BC Round #37 1002
    poj 3071 概率dp
    poj 2151 概率dp
    zoj 3460 二分+二分图匹配
  • 原文地址:https://www.cnblogs.com/zhongxuan/p/4795673.html
Copyright © 2011-2022 走看看