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. Django-自己写的py文件调用models&Non-ASCII character报错&url接收参数

    1.这个设置是网上能查到的最多的,但是没解决我的问题: Django的models.py在外部独立使用,新建一个文件夹,和monitor1目录平级 import sys,os sys.path.app ...

  2. RabbitMQ 核心概念

    目录 RabbitMQ 特点 AMQP 协议 RabbitMQ 消息传递机制 Message Exchange 1. 简介 2. 类型 3. 属性 RabbitMQ 特点 RabbitMQ 相较于其他 ...

  3. 小程序使用wxParse插件解析html标签图片间距问题

    转自:https://www.cnblogs.com/likun123/p/9543376.html 小程序解析html标签,就需要用到wxParse啦.但是在解析连续图片的时候,会发现图片之间会有间 ...

  4. JavaScript世界万物诞生记

    作者:manxisuo链接:https://zhuanlan.zhihu.com/p/22989691来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. 一. 无中生有 起 ...

  5. 【CSS】使用CSS控制文字过多自动省略号

    使用CSS可以设置一下样式: <style> u,small{ overflow: hidden; text-overflow: ellipsis; display: -webkit-bo ...

  6. Git以及github的使用方法(五),暂存区和工作区

    Git和其他版本控制系统如SVN的一个不同之处就是有暂存区的概念. 先来看名词解释. 工作区(Working Directory) 就是你在电脑里能看到的目录,比如我的learngit文件夹就是一个工 ...

  7. SD卡操作相关的工具SDCardUtils

    SD卡操作相关的工具 package com.flyou.utils; import java.io.File; import android.os.Environment; import andro ...

  8. C++11 并发指南四(<future> 详解一 std::promise 介绍)(转)

    前面两讲<C++11 并发指南二(std::thread 详解)>,<C++11 并发指南三(std::mutex 详解)>分别介绍了 std::thread 和 std::m ...

  9. Mina、Netty、Twisted一起学(七):公布/订阅(Publish/Subscribe)

    消息传递有非常多种方式.请求/响应(Request/Reply)是最经常使用的.在前面的博文的样例中.非常多都是採用请求/响应的方式.当server接收到消息后,会马上write回写一条消息到clie ...

  10. jquery中text(),html(),val()在取值上的区别

    1.html():读取和修改一个元素的HTML内容: 2.text():读取和修改一个元素的文本内容: 3.val():读取和修改一个表单元素的value字段值.