CoreData使用
1.如果想创建一个带有coreData的程序,要在项目初始化的时候勾选中
2.创建完成之后,会发现在AppDelegate里多出了几个属性,和2个方法
- <span style="font-size:18px;">
- @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
- @property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
- @property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- - (void)saveContext;
- - (NSURL *)applicationDocumentsDirectory;</span>
managedObjectContext (被管理的数据上下文)操作实际内容(操作持久层)作用:插入数据,查询数据,删除数据
NSManagedObjectModel(被管理的数据模型)数据库所有表格或数据结构,包含各实体的定义信息 作用:添加实体的属性,建立属性之间的关系操作方法:视图编辑器,或代码
NSPersistentStoreCoordinator(持久化存储助理)相当于数据库的连接器 作用:设置数据存储的名字,位置,存储方式,和存储时机
方法saveContext表示:保存数据到持久层(数据库)
方法applicationDocumentsDirectory表示:应用程序沙箱下的Documents目录路径
3.如果想创建一个实体对象的话,需要点击.xcdatamodel,Add Entity,添加想要的字段
4.生成对象文件,command+n,然后选中CoreData里的NSManagerObjectSubClass进行关联,选中实体创建
5.添加数据
- Person *newPerson = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
- if (newPerson == nil){
- NSLog(@"Failed to create the new person.");
- return NO;
- }
- newPerson.firstName = paramFirstName;
- newPerson.lastName = paramLastName;
- newPerson.age = [NSNumber numberWithUnsignedInteger:paramAge];
- NSError *savingError = nil;
- if ([self.managedObjectContext save:&savingError]){
- return YES;
- } else {
- NSLog(@"Failed to save the new person. Error = %@", savingError);
- }
NSEntityDescription(实体结构)相当于表格结构
6.取出数据查询
- /* Create the fetch request first */
- NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
- /* Here is the entity whose contents we want to read */
- NSEntityDescription *entity =
- [NSEntityDescription
- entityForName:@"Person"
- inManagedObjectContext:self.managedObjectContext];
- /* Tell the request that we want to read the
- contents of the Person entity */
- [fetchRequest setEntity:entity];
- NSError *requestError = nil;
- /* And execute the fetch request on the context */
- NSArray *persons =
- [self.managedObjectContext executeFetchRequest:fetchRequest
- error:&requestError];
- /* Make sure we get the array */
- if ([persons count] > 0){
- /* Go through the persons array one by one */
- NSUInteger counter = 1;
- for (Person *thisPerson in persons){
- NSLog(@"Person %lu First Name = %@",
- (unsigned long)counter,
- thisPerson.firstName);
- NSLog(@"Person %lu Last Name = %@",
- (unsigned long)counter,
- thisPerson.lastName);
- NSLog(@"Person %lu Age = %ld",
- (unsigned long)counter,
- (unsigned long)[thisPerson.age unsignedIntegerValue]);
- counter++;
- }
- } else {
- NSLog(@"Could not find any Person entities in the context.");
- }
7.删除数据
- /* Create the fetch request first */
- NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
- /* Here is the entity whose contents we want to read */
- NSEntityDescription *entity =
- [NSEntityDescription
- entityForName:@"Person"
- inManagedObjectContext:self.managedObjectContext];
- /* Tell the request that we want to read the
- contents of the Person entity */
- [fetchRequest setEntity:entity];
- NSError *requestError = nil;
- /* And execute the fetch request on the context */
- NSArray *persons =
- [self.managedObjectContext executeFetchRequest:fetchRequest
- error:&requestError];
- if ([persons count] > 0){
- /* Delete the last person in the array */
- Person *lastPerson = [persons lastObject];
- [self.managedObjectContext deleteObject:lastPerson];
- NSError *savingError = nil;
- if ([self.managedObjectContext save:&savingError]){
- NSLog(@"Successfully deleted the last person in the array.");
- } else {
- NSLog(@"Failed to delete the last person in the array.");
- }
- } else {
- NSLog(@"Could not find any Person entities in the context.");
- }
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使用的更多相关文章
- iOS基本数据库存储方式 - CoreData
CoreData 创建模型文件的过程 1.选择模板 2.添加实体 3.添加实体的属性[注意]属性的首字母必须小写 一.CoreData管理类(必备以下三个类对象) 1.CoreData数据操作的上下文 ...
- iOS CoreData 中 objectID 的不变性
关于 CoreData的 objectID 官方文档有这样的表述:新建的Object还没保存到持久化存储上,那么它的objectID是临时id,而保存之后,就是持久化的id,不会再变化了. 那么,我想 ...
- CoreData __ 基本原理
操作过程 Context想要获取值,先要告诉连接器,我要什么东西 链接器再告诉store, 你给我什么东西, store去找 找到之后返回给链接器,链接器再返回给Context Co ...
- iOS CoreData primitive accessor
Given an entity with an attribute firstName, Core Data automatically generates firstName, setFirstNa ...
- 初识CoreData与详解
Core Data数据持久化是对SQLite的一个升级,它是iOS集成的,在说Core Data之前,我们先说说在CoreData中使用的几个类. (1)NSManagedObjectModel(被管 ...
- CoreData教程
网上关于CoreData的教程能搜到不少,但很多都是点到即止,真正实用的部分都没有讲到,而基本不需要的地方又讲了太多,所以我打算根据我的使用情况写这么一篇实用教程.内容将包括:创建entity.创建r ...
- CoreData和SQLite多线程访问时的线程安全
关于CoreData和SQLite多线程访问时的线程安全问题 数据库读取操作一般都是多线程访问的.在对数据进行读取时,我们要保证其当前状态不能被修改,即读取时加锁,否则就会出现数据错误混乱.IOS中常 ...
- IOS数据存储之CoreData使用优缺点
前言: 学习了Sqlite数据之后认真思考了一下,对于已经习惯使用orm数据库的开发者或者对sql语句小白的开发者来说该如何做好数据库开发呢?这个上网搜了一下?看来总李多虑了!apple 提供了一种数 ...
- iOS开发之表视图爱上CoreData
在接触到CoreData时,感觉就是苹果封装的一个ORM.CoreData负责在Model的实体和sqllite建立关联,数据模型的实体类就相当于Java中的JavaBean, 而CoreData的功 ...
- CoreData
之前在学习使用SQLite时, 需要编写大量的sql语句,完成数据的增删改查,但对于不熟悉sql语句的开发人员来说,难度较大,调试程序比较困难. 由此出现CoreData框架,将sql的操作转换成为对 ...
随机推荐
- POJ - 2391 最大流
题目链接:http://poj.org/problem?id=2391 今天掉坑多次. 做了几道题,发现从源点出来的边和进入汇点的边都在题目中出来过. POJ真是坑,交G++一直wa,检查代码检查了好 ...
- react-native 判断是不是IPhone X
import { Platform, Dimensions } from 'react-native'; // iPhoneX const X_WIDTH = 375; const X_HEIGHT ...
- VUE2.0 【v-html】标签使用技巧
<div class="active-rules"> <div class="weui-weixin-content" id="ru ...
- Latex algorithm
方式一 需要包含的 \usepackage[noend]{algpseudocode} \usepackage{algorithmicx,algorithm} 源码 \begin{algorithm} ...
- 《从零开始搭建游戏服务器》项目管理工具Maven
简介 什么是Maven?Maven是一个项目管理和综合工具,提供了开发人员构建一个完整的生命周期框架. Maven使用标准的目录结构和默认构建生命周期,在多个开发团队环境时,Maven可以设置按标准在 ...
- [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 ...
- BZOJ 2085 [POI2010] Hamsters
题面 Description Tz养了一群仓鼠,他们都有英文小写的名字,现在Tz想用一个字母序列来表示他们的名字,只要他们的名字是字母序列中的一个子串就算,出现多次可以重复计算.现在Tz想好了要出现多 ...
- Android 源码编译记录
问题1:Can't locate Switch.pm in @INC (you may need to install the Switch module) (@INC contains: /etc/ ...
- iOS --SKView类
SKView类 继承自 UIView:UIResponder:NSObject 符合 NSCoding(UIView)UIAppearance(UIView)UIAppearanceContainer ...
- iOS--实时监控网络状态的改变
在网络应用中,有的时候需要对用户设备的网络状态进行实时监控,有两个目的: (1)让用户了解自己的网络状态,防止一些误会(比如怪应用无能) (2)根据用户的网络状态进行智能处理,节省用户流量,提高用户体 ...