iOS Core Data

作者: iOS_成才录 | 来源:发表于2015-11-12 19:28 被阅读772次

一、简介

  • Core Data框架提供了对象-关系映射(ORM)的功能,即能够将OC对象转化成数据,保存在SQLite3数据库文件中,也能够将保存在数据库中的数据还原成OC对象。
    • 在此数据操作期间,不需要编写任何SQL语句。使用此功能,要添加CoreData.framework和导入主头文件<CoreData/CoreData.h>

二、Core Data 认识

  • Core Data是对SQLite数据库的封装
  • Core Data优缺点:
    • 优点:能够合理管理内存,避免使用sql的麻烦,高效
    • 缺点:它使基于SQLite的,所以并没有SQLite高效
  • Core Data本身并不是一个并发安全的架构,所以在多线程中使用Core Data使用会有如下问题:
    • Core Data中的NSManagedObjectContext在多线程中不安全
    • 如果想要多线程方法Core Data的话,最好的方法就是:一个线程对应一个NSManagedObjectContext
    • 每个NSManagedObjectContext对象实例都可以使用同一个NSPersistentStoreCoordinator实例,因为NSManagedObjectContext会在使用NSPersistentStoreCoordinator前加锁

三、Core Data 基本介绍

Core Data主要对象.png 依赖关系.png
  • NSManagedObjectContext --- 数据上下文

    • 操作 -> 实际内容(操作持久层),进行增加删改操作
    • 1.数据上下文初始化的后,必须设置持久化存储助理
  • NSManagedObjectModel --- 数据模型

    • 数据库所有表格或数据结构,包含各实体的定义信息
    • 作用:添加实体的属性,建立属性之间的关系
    • 操作方法:视图编辑器,或代码
    • 初始化
      • 通过文件创建,初始化必须依赖.momd文件路径,而.momd文件由.xcdatamodeld文件编译而来
  • NSPersistentStoreCoordinator --- 持久化存储助理

    • 作用:设置数据存储的名字,位置,存储方式
    • 初始化:必须依赖NSManagedObjectModel,之后要指定持久化存储的数据类型,默认的是NSSQLiteStoreType,即SQLite数据库;并指定存储路径为Documents目录下,以及数据库名称
  • NSManagedObject

  • 相当于数据库中的表格记录
  • NSFetchRequest 请求

    • 相当于查询语句
  • ** NSEntityDescription 实体结构 **

    • 相当于表格结构
  • .xcdatamodeld

    • .xcdatamodel文件,用数据模型编辑器编辑,编译后为.momd或.mom文件

三、注意

1、 牢记:一个数据库对应一个上下文

  • 需求: 如果我们有两个模型xcdatamodeld文件,如何让所有的模型文件中的实体对应的表结构都放在一个数据库文件中去呢?与如何实现放在不同的数据库文件中去呢?
    • 放在一个数据库文件中:
      • 如果我们创建NSManagedObjectModel对象的时候传入的是main bounlde,默认是把所以的模型文件中的表结构创建到一张数据库文件中去的。 main bounlde.png
    • 放在不同的数据库文件中:
      • 实现:就是要,创建两个上下文,然后指定不同的NSManagedObjectModel(加载不同的xcdatamodeld文件)。


        不同数据库,实现方法.png

打开CoreData的SQL语句输出开关

  • 1.打开Product,点击EditScheme...
  • 2.点击Arguments,在ArgumentsPassed On Launch中添加2项
    • 1> -com.apple.CoreData.SQLDebug
    • 2> 1 第一步.png
      第二步.png

四、基本使用

  • Company.xcdatamodeld文件创建


    xcdatamodeld文件.png

#import "JPViewController.h"
#import <CoreData/CoreData.h> // 导入头文件
#import "Employee.h"

@interface JPViewController (){
    NSManagedObjectContext *_context;
}

@end

@implementation JPViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //使用CoreData来保存数据
    
    //1.初始化上下文
    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
    
    //2.添加持久化存储
    //2.1模型文件 描述表结构的文件 也就是(Company.xcdatamodeld)这个文件
#warning 补充 ,如bundles传nil 会从主bundle加载所有的模型文件,把里面表结构都放在一个数据库文件
    NSManagedObjectModel *companyModel = [NSManagedObjectModel mergedModelFromBundles:nil];
    
    //2.2持久化存储调用器
    NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:companyModel];
    
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    //数据库的完整文件路径
    NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"];
    
    //保存一个sqite文件的话,必要知道表结构和sqlite的文件路径
    //2.3 告诉coredate数据存储在一个sqlite文件
    NSError *error = nil;
    [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:&error];
    
    if (error) {
        NSLog(@"%@",error);
    }
    
    context.persistentStoreCoordinator = store;
    _context = context;
}

- (IBAction)addEmployee {
    
    //添加员工
    //1.创建一个员工对象
    //用coredata创建对象不能使用下面的方法
    //Employee *emp = [[Employee alloc] init];
    
    
    Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];
    emp.name = @"wangwu";
    emp.height = @(1.50);
    emp.createDate = [NSDate date];
    
    //保存员工信息
    NSError *error = nil;
    [_context save:&error];
    
    if (error) {
        NSLog(@"%@",error);
    }

//    for (int i = 0; i < 10; i++) {
//        Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];
//        emp.name = [NSString stringWithFormat:@"zhangsan%d",i];
//        emp.height = @(1.98);
//        emp.createDate = [NSDate date];
//        
//        //保存员工信息
//        NSError *error = nil;
//        [_context save:&error];
//        
//        if (error) {
//            NSLog(@"%@",error);
//        }
//        [NSThread sleepForTimeInterval:1];
//        NSLog(@"=========%d",i);
//        
//    }
   
    
}

#pragma mark 查找员工信息
- (IBAction)findEmployee {
    
    //查找数据
    //1.创建请求对象,指定要查找的表
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
    
    //2.时间排序
    NSSortDescriptor *dateSort = [NSSortDescriptor sortDescriptorWithKey:@"createDate" ascending:YES];//YES代表升序 NO 降序
    request.sortDescriptors = @[dateSort];
    
    
    //3.过滤条件 只想查找 zhangsan8
//    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"zhangsan8"];
//    request.predicate = pre;
    
    
    //分页语句 10 5条 (0 ,5) (5,10)
//    request.fetchOffset = 5;
//    request.fetchLimit = 5;
    
    //3.执行请求
    NSError *error = nil;
    NSArray *allEmployee =  [_context executeFetchRequest:request error:&error];
    if (error) {
        NSLog(@"%@",error);
    }
    
    //NSLog(@"%@",allEmployee);
    for (Employee *emp in allEmployee) {
        NSLog(@"%@ %@ %@",emp.name,emp.height,emp.createDate);
    }
}


#pragma 更新员工信息
- (IBAction)updateEmployee {
    
    //查找数据
    //1.创建请求对象,指定要查找的表
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
    
    //2.时间排序
    NSSortDescriptor *dateSort = [NSSortDescriptor sortDescriptorWithKey:@"createDate" ascending:YES];//YES代表升序 NO 降序
    request.sortDescriptors = @[dateSort];
    
    
   //过滤条件 只想查找 zhangsan8
   NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"zhangsan8"];
   request.predicate = pre;
    
    
    //3.执行请求
    NSArray *allEmployee =  [_context executeFetchRequest:request error:nil];
    
    NSLog(@"%@",allEmployee);
    //更新zhangsan8的身高为2米
    for (Employee *emp in allEmployee) {
        emp.height = @(2);
    }
    
    //保存更改的信息
    [_context save:nil];
}

#pragma mark 删除员工信息
- (IBAction)deleteEmployee {
    //查找数据
    //1.创建请求对象,指定要查找的表
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
    
    //2.时间排序
    NSSortDescriptor *dateSort = [NSSortDescriptor sortDescriptorWithKey:@"createDate" ascending:YES];//YES代表升序 NO 降序
    request.sortDescriptors = @[dateSort];
    
    
    //过滤条件 只想查找 zhangsan8
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"zhangsan8"];
    request.predicate = pre;
    
    
    //3.执行请求
    NSArray *allEmployee =  [_context executeFetchRequest:request error:nil];
    
    NSLog(@"%@",allEmployee);
    //删除zhangsan8的信息
    for (Employee *emp in allEmployee) {
        [_context deleteObject:emp];
    }

}


#pragma mark 复杂查询
- (IBAction)fuzaFind {
    //查找数据
    //1.创建请求对象,指定要查找的表
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
    
    //2.时间排序
    NSSortDescriptor *dateSort = [NSSortDescriptor sortDescriptorWithKey:@"createDate" ascending:YES];//YES代表升序 NO 降序
    request.sortDescriptors = @[dateSort];
    
    
    //3.过滤条件 只想查找 zhangsan8
    //a 查找名为zhangsan 并且身高大于等1.9
    //NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@ AND height >= %lf",@"zhangsan",1.30];
    
    //b.查找名字以zh开头 并且身高大于1.3
    //以什么BEGINSWITH
    //c代表不区分大小写
    //NSPredicate *pre = [NSPredicate predicateWithFormat:@"name BEGINSWITH[c] %@ AND height >= %lf",@"abc",1.30];
    
    //c.查找名字以san结尾 ,并用身高大于1.3
    //NSPredicate *pre = [NSPredicate predicateWithFormat:@"name ENDSWITH[c] %@ AND height >= %lf",@"cent",1.30];
    
    //4.模糊查询
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name like[c] %@",@"Li*"];
    
    request.predicate = pre;
    
    //4.执行请求
    NSError *error = nil;
    NSArray *allEmployee =  [_context executeFetchRequest:request error:&error];
    if (error) {
        NSLog(@"%@",error);
    }
    
    //NSLog(@"%@",allEmployee);
    for (Employee *emp in allEmployee) {
        NSLog(@"%@ %@ %@",emp.name,emp.height,emp.createDate);
    }
}
@end

相关文章

网友评论

    本文标题:iOS Core Data

    本文链接:https://www.haomeiwen.com/subject/ntzfhttx.html