1.如果想创建一个带有coreData的程序,要在项目初始化的时候勾选中

2.创建完成之后,会发现在AppDelegate里多出了几个属性,和2个方法

  1. <span style="font-size:18px;">
  2. @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
  3. @property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
  4. @property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
  5. - (void)saveContext;
  6. - (NSURL *)applicationDocumentsDirectory;</span>

managedObjectContext (被管理的数据上下文)操作实际内容(操作持久层)作用:插入数据,查询数据,删除数据

NSManagedObjectModel(被管理的数据模型)数据库所有表格或数据结构,包含各实体的定义信息 作用:添加实体的属性,建立属性之间的关系操作方法:视图编辑器,或代码

NSPersistentStoreCoordinator(持久化存储助理)相当于数据库的连接器 作用:设置数据存储的名字,位置,存储方式,和存储时机

方法saveContext表示:保存数据到持久层(数据库)

方法applicationDocumentsDirectory表示:应用程序沙箱下的Documents目录路径

3.如果想创建一个实体对象的话,需要点击.xcdatamodel,Add Entity,添加想要的字段

4.生成对象文件,command+n,然后选中CoreData里的NSManagerObjectSubClass进行关联,选中实体创建

5.添加数据

  1. Person *newPerson = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
  2. if (newPerson == nil){
  3. NSLog(@"Failed to create the new person.");
  4. return NO;
  5. }
  6. newPerson.firstName = paramFirstName;
  7. newPerson.lastName = paramLastName;
  8. newPerson.age = [NSNumber numberWithUnsignedInteger:paramAge];
  9. NSError *savingError = nil;
  10. if ([self.managedObjectContext save:&savingError]){
  11. return YES;
  12. } else {
  13. NSLog(@"Failed to save the new person. Error = %@", savingError);
  14. }

NSEntityDescription(实体结构)相当于表格结构

6.取出数据查询

  1. /* Create the fetch request first */
  2. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  3. /* Here is the entity whose contents we want to read */
  4. NSEntityDescription *entity =
  5. [NSEntityDescription
  6. entityForName:@"Person"
  7. inManagedObjectContext:self.managedObjectContext];
  8. /* Tell the request that we want to read the
  9. contents of the Person entity */
  10. [fetchRequest setEntity:entity];
  11. NSError *requestError = nil;
  12. /* And execute the fetch request on the context */
  13. NSArray *persons =
  14. [self.managedObjectContext executeFetchRequest:fetchRequest
  15. error:&requestError];
  16. /* Make sure we get the array */
  17. if ([persons count] > 0){
  18. /* Go through the persons array one by one */
  19. NSUInteger counter = 1;
  20. for (Person *thisPerson in persons){
  21. NSLog(@"Person %lu First Name = %@",
  22. (unsigned long)counter,
  23. thisPerson.firstName);
  24. NSLog(@"Person %lu Last Name = %@",
  25. (unsigned long)counter,
  26. thisPerson.lastName);
  27. NSLog(@"Person %lu Age = %ld",
  28. (unsigned long)counter,
  29. (unsigned long)[thisPerson.age unsignedIntegerValue]);
  30. counter++;
  31. }
  32. } else {
  33. NSLog(@"Could not find any Person entities in the context.");
  34. }

7.删除数据

  1. /* Create the fetch request first */
  2. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  3. /* Here is the entity whose contents we want to read */
  4. NSEntityDescription *entity =
  5. [NSEntityDescription
  6. entityForName:@"Person"
  7. inManagedObjectContext:self.managedObjectContext];
  8. /* Tell the request that we want to read the
  9. contents of the Person entity */
  10. [fetchRequest setEntity:entity];
  11. NSError *requestError = nil;
  12. /* And execute the fetch request on the context */
  13. NSArray *persons =
  14. [self.managedObjectContext executeFetchRequest:fetchRequest
  15. error:&requestError];
  16. if ([persons count] > 0){
  17. /* Delete the last person in the array */
  18. Person *lastPerson = [persons lastObject];
  19. [self.managedObjectContext deleteObject:lastPerson];
  20. NSError *savingError = nil;
  21. if ([self.managedObjectContext save:&savingError]){
  22. NSLog(@"Successfully deleted the last person in the array.");
  23. } else {
  24. NSLog(@"Failed to delete the last person in the array.");
  25. }
  26. } else {
  27. NSLog(@"Could not find any Person entities in the context.");
  28. }

8.排序

    NSSortDescriptor *ageSort = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];  

    NSSortDescriptor *firstNameSort = [[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES];  

    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:ageSort,firstNameSort, nil nil];  

    fetchRequest.sortDescriptors = sortDescriptors;

    //  注意 ascending:YES 属性决定排序顺序

CoreData使用的更多相关文章

  1. iOS基本数据库存储方式 - CoreData

    CoreData 创建模型文件的过程 1.选择模板 2.添加实体 3.添加实体的属性[注意]属性的首字母必须小写 一.CoreData管理类(必备以下三个类对象) 1.CoreData数据操作的上下文 ...

  2. iOS CoreData 中 objectID 的不变性

    关于 CoreData的 objectID 官方文档有这样的表述:新建的Object还没保存到持久化存储上,那么它的objectID是临时id,而保存之后,就是持久化的id,不会再变化了. 那么,我想 ...

  3. CoreData __ 基本原理

    操作过程 Context想要获取值,先要告诉连接器,我要什么东西 链接器再告诉store, 你给我什么东西, store去找 找到之后返回给链接器,链接器再返回给Context          Co ...

  4. iOS CoreData primitive accessor

    Given an entity with an attribute firstName, Core Data automatically generates firstName, setFirstNa ...

  5. 初识CoreData与详解

    Core Data数据持久化是对SQLite的一个升级,它是iOS集成的,在说Core Data之前,我们先说说在CoreData中使用的几个类. (1)NSManagedObjectModel(被管 ...

  6. CoreData教程

    网上关于CoreData的教程能搜到不少,但很多都是点到即止,真正实用的部分都没有讲到,而基本不需要的地方又讲了太多,所以我打算根据我的使用情况写这么一篇实用教程.内容将包括:创建entity.创建r ...

  7. CoreData和SQLite多线程访问时的线程安全

    关于CoreData和SQLite多线程访问时的线程安全问题 数据库读取操作一般都是多线程访问的.在对数据进行读取时,我们要保证其当前状态不能被修改,即读取时加锁,否则就会出现数据错误混乱.IOS中常 ...

  8. IOS数据存储之CoreData使用优缺点

    前言: 学习了Sqlite数据之后认真思考了一下,对于已经习惯使用orm数据库的开发者或者对sql语句小白的开发者来说该如何做好数据库开发呢?这个上网搜了一下?看来总李多虑了!apple 提供了一种数 ...

  9. iOS开发之表视图爱上CoreData

    在接触到CoreData时,感觉就是苹果封装的一个ORM.CoreData负责在Model的实体和sqllite建立关联,数据模型的实体类就相当于Java中的JavaBean, 而CoreData的功 ...

  10. CoreData

    之前在学习使用SQLite时, 需要编写大量的sql语句,完成数据的增删改查,但对于不熟悉sql语句的开发人员来说,难度较大,调试程序比较困难. 由此出现CoreData框架,将sql的操作转换成为对 ...

随机推荐

  1. POJ - 2391 最大流

    题目链接:http://poj.org/problem?id=2391 今天掉坑多次. 做了几道题,发现从源点出来的边和进入汇点的边都在题目中出来过. POJ真是坑,交G++一直wa,检查代码检查了好 ...

  2. react-native 判断是不是IPhone X

    import { Platform, Dimensions } from 'react-native'; // iPhoneX const X_WIDTH = 375; const X_HEIGHT ...

  3. VUE2.0 【v-html】标签使用技巧

    <div class="active-rules"> <div class="weui-weixin-content" id="ru ...

  4. Latex algorithm

    方式一 需要包含的 \usepackage[noend]{algpseudocode} \usepackage{algorithmicx,algorithm} 源码 \begin{algorithm} ...

  5. 《从零开始搭建游戏服务器》项目管理工具Maven

    简介 什么是Maven?Maven是一个项目管理和综合工具,提供了开发人员构建一个完整的生命周期框架. Maven使用标准的目录结构和默认构建生命周期,在多个开发团队环境时,Maven可以设置按标准在 ...

  6. [Machine Learning with Python] Data Visualization by Matplotlib Library

    Before you can plot anything, you need to specify which backend Matplotlib should use. The simplest ...

  7. BZOJ 2085 [POI2010] Hamsters

    题面 Description Tz养了一群仓鼠,他们都有英文小写的名字,现在Tz想用一个字母序列来表示他们的名字,只要他们的名字是字母序列中的一个子串就算,出现多次可以重复计算.现在Tz想好了要出现多 ...

  8. Android 源码编译记录

    问题1:Can't locate Switch.pm in @INC (you may need to install the Switch module) (@INC contains: /etc/ ...

  9. iOS --SKView类

    SKView类 继承自 UIView:UIResponder:NSObject 符合 NSCoding(UIView)UIAppearance(UIView)UIAppearanceContainer ...

  10. iOS--实时监控网络状态的改变

    在网络应用中,有的时候需要对用户设备的网络状态进行实时监控,有两个目的: (1)让用户了解自己的网络状态,防止一些误会(比如怪应用无能) (2)根据用户的网络状态进行智能处理,节省用户流量,提高用户体 ...