iOS CoreData的使用和简介

22 篇文章 0 订阅

什么是CoreData

在现代应用开发中,关于做数据持久化处理中,越来越多的人使用CoreData.因为用苹果的话来说它可以节约30%—70%的代码量 .(对于这个说法,大家可以各抒起见,欢迎吐槽),当然,对比与其他几个数据持久化的操作(如:写入,归档,SQLite),个人认为还是有好多好处的,它对sqlite进行了分装,只能用在iphone上

概念

下面我们来看一下它的概念
1.Core Data 是数据持久化存储的最佳方式
2.数据最终的存储类型可以是:SQLite数据库,XML,二进制, 内存里或自定义数据类型

好处

那么它有什么好处呢
1.能够合理管理内存,避免使用sql的麻烦,高效
2.支持可视化建模
3.支持数据库升级 (关键点) (例如数据库中添加字段)

构成

下面我们来了解一下它的构成,当然在后面还会有详细的介绍
(1)NSManagedObjectContext(被管理的数据上下文)(数据管理:临时数据库)
操作实际内容(操作持久层)
作用:插入数据,查询数据,删除数据
(2)NSManagedObjectModel(被管理的数据模型,模具)
数据库所有表格或数据结构,包含各实体的定义信息
作用:添加实体的属性,建立属性之间的关系
操作方法:视图编辑器,或代码
(3)NSPersistentStoreCoordinator(持久化存储助理)(数据连接器)
相当于数据库的连接器 与数据库直接打交道
作用:设置数据存储的名字,位置,存储方式,和存储时机
(4)NSManagedObject(被管理的数据记录)
相当于数据库中的表格记录
(5)NSFetchRequest(获取数据的请求)
相当于查询语句
(6)NSEntityDescription(实体结构)
相当于表格结构
(7)后缀为.xcdatamodeld的包
里面是.xcdatamodel文件,用数据模型编辑器编辑
编译后为.momd或.mom文件

属性和方法简介

我们简单介绍了CoreData创建的基本界面操作,今天我们简单介绍一下关于勾选user coreData后在AppDalageta.h生成的一些属性和方法的意义和使用.
在建立工程时,点击 use core Data 时
系统会在AppDelegate.h 中生成一些系统自带的方法

//被管理对象的上下文又叫数据管理器 是一个临时数据库 执行增删改查操作, 但这个时候并不改变真实数据库文件 如想影响真实数据局文件,要用Save操作
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
//被管理对象模型 又叫数据模拟器 管理多个对象
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
//持久化存储助理 又叫做数据连接器 是CoreData中的核心类,添加持久化存储 真实的与数据库文件打交道
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

在AppDelegate.m中的实现

//获取沙盒下document文件夹路径  不仅可以获取本地的也可以获取远程上的(从服务器上获取)
- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.lanou.Lesson04CoreData" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

//重写get方法
- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    //获取可视化建模文件路径  .xcdatamodeld 被编译后就是.momd
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Lesson04CoreData" withExtension:@"momd"];
    //创建数据模型器 与可视化建模文件建立关系
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

    // Create the coordinator and store
    //创建持久化存储助理, 与数据模型器建立关系
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    //获取数据库文件路径
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Lesson04CoreData.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    /*
     参数1:制定存储类型
     参数2:配置信息,暂时没用
     参数3:数据库文件路径
     参数4:选项信息,支持数据库升级,迁徙
     参数5:错误信息
     */
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:@{NSMigratePersistentStoresAutomaticallyOption:@YES,NSInferMappingModelAutomaticallyOption :@YES} error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        //程序中断,方便调试使用
        abort();
    }

    return _persistentStoreCoordinator;
}

- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    //获取一个持久化存储助理
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    //创建被管理对象上下文,指定在主线程中进行数据操作
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    //给被管理对象上下文指定持久化存储助理
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    //获取当前上下文对象
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        //被管理对象上下文调用Save方法, 真实的改变数据库文件

        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

关于数据库的增删改查的操作

在viewController.m中关联button的方法中实现
添加数据到数据库中
1.通过实体描述对象创建实体类
Student *student =[NSEntityDescription insertNewObjectForEntityForName:@”Student” inManagedObjectContext:self.managedObjectContext];
2.给实体类赋值

3.要想保存到真实的数据库中 必须调用被管理对象的上下文的Save方法
NSError *error = nil;
[self.managedObjectContext save:&error];
if (error) {
NSLog(@”保存失败”);
}
else {
[self.dataArray addObject:student];
//让实体对象显示在cell上
NSIndexPath *indenPath = [NSIndexPath indexPathForRow:self.dataArray.count -1 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[indenPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
在viewController.m 中的viewDidLoad中实现下面方法

self.dataArray = [[NSMutableArray alloc]init];
    //从应用程序中的代理类被管理对象上下文
//    AppDelegate *app = [UIApplication  sharedApplication].delegate;
//    self.managedObjectContext = [app managedObjectContext];
    self.managedObjectContext = [(AppDelegate *)[UIApplication sharedApplication].delegate managedObjectContext];

    //从数据库中查询数据
    //先创建一个查询请求对象
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Student"];

    //条件查询 通过谓词设置条件 多个条件使用and连接
    NSPredicate  *predicate = [NSPredicate predicateWithFormat:@"teacher = %@",self.teacher];

    [request setPredicate:predicate];

    //排序查询对象
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
    [request setSortDescriptors:@[sortDescriptor]];
    //执行查询请求,获取查询结果
 NSArray *resultArray = [self.managedObjectContext executeFetchRequest:request error:nil];
    if (resultArray > 0) {
        [self.dataArray addObjectsFromArray:resultArray];
        [self.tableView reloadData];
    }

注意:在这里条件查询是可选的,通过谓语设置条件 多个条件使用and连接
今天就和大家介绍到这里,后面会给大家介绍关于CoreData的两个实体类建议福关系和属性,数据库升级的内容,谢谢大家

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值