iOS CoreData总结
相关主要类:
NSManagedObjectContext 管理对象,上下文,持久性存储模型对象,处理数据与应用的交互
NSManagedObjectModel 被管理的数据模型,数据结构
NSPersistentStoreCoordinator 添加数据库,设置数据存储的名字,位置,存储方式
NSManagedObject 被管理的数据记录
NSFetchRequest 数据请求
NSEntityDescription 表格实体结构
相关操作:
Editor -> Add Model Version : 创建新的数据库
Editor -> Create NSManagerObject SubClass 创建模型对象文件
注意点:
1.Codegen 属性要设置为 None ,不然再手动生成显示的模型对象文件多报错。(默认是隐式文件,但是使用实体类时,无法引用文件)
2.
// 创建托管对象模型 @“lwCoreDataDemo”是CoreData的文件名;@“momd”是.xcdatamodel文件,用数据模型编辑器编辑编译后为.momd或.mom文件,所以就写@“momd”,
NSURL *modelpath = [[NSBundle mainBundle] URLForResource:@"lwCoreDataDemo" withExtension:@"momd"];
NSLog(@"------modelpath:%@",modelpath);
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelpath];
1.初始化
2.增删改查操作
3.数据量迁移:主要设置,不然无法找到 当前的模型文件
//请求自动轻量级迁移
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
nil];
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:datapath] options:options error:nil];
4.多表操作
// 多表插入
Student * student = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:_context];
student.age = arc4random()%10;
student.name = @"jack"; Course *course = [NSEntityDescription insertNewObjectForEntityForName:@"Course" inManagedObjectContext:_context];
course.course_id = arc4random()%20;
course.course_name = @"英语";
// [student addStu_course:[NSSet setWithObject:course]];
student.stu_course = [NSSet setWithObject:course]; Classes *classes = [NSEntityDescription insertNewObjectForEntityForName:@"Classes" inManagedObjectContext:_context];
classes.class_name = [NSString stringWithFormat:@"高二(%u)班",arc4random()%3];
classes.class_id = arc4random()%10;
student.stu_classes = classes;
// 多表查询
NSFetchRequest *requst1 = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
requst1.predicate = [NSPredicate predicateWithFormat:@"stu_classes.class_name=%@",@"高二(1)班"]; NSArray *res1 = [_context executeFetchRequest:requst1 error:nil];
[res1 enumerateObjectsUsingBlock:^(Student * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"Student:[name:%@,age:%hd]",obj.name,obj.age);
}];
5.代码
封装的工具类:
.h文件

//
// LWCoreDataManager.h
// lwCoreDataDemo
//
// Created by LWQ on 2020/6/29.
// Copyright 2020 LWQ. All rights reserved.
// #import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#import "Person+CoreDataClass.h"
#import "Student+CoreDataClass.h"
#import "Classes+CoreDataClass.h"
#import "Course+CoreDataClass.h" @interface LWCoreDataManager : NSObject
@property (nonatomic, strong) NSManagedObjectContext * context; + (instancetype)share; - (void)insert;
- (NSArray<Person *>*)query;
- (void)delete;
- (void)update; + (NSString *)personString:(Person *)p;
@end
LWCoreDataManager.h
.m文件

//
// LWCoreDataManager.m
// lwCoreDataDemo
//
// Created by LWQ on 2020/6/29.
// Copyright 2020 LWQ. All rights reserved.
// #import "LWCoreDataManager.h" @implementation LWCoreDataManager + (instancetype)share
{
static LWCoreDataManager *instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[LWCoreDataManager alloc] init];
[instance installConfigure];
});
return instance;
} //安装配置
- (void)installConfigure
{
// 创建托管上下文对象
_context = [[NSManagedObjectContext alloc] initWithConcurrencyType:(NSMainQueueConcurrencyType)]; // 创建托管对象模型
NSURL *modelpath = [[NSBundle mainBundle] URLForResource:@"lwCoreDataDemo" withExtension:@"momd"];
NSLog(@"------modelpath:%@",modelpath);
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelpath]; // 创建持久化存储调度器
NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; // 创建数据库文件并关联持久化存储调度器
NSString *datapath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
datapath = [datapath stringByAppendingFormat:@"/%@.sqlite",@"lwCoreDataDemo"];
NSLog(@"------datapath:%@",datapath); //请求自动轻量级迁移
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
nil];
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:datapath] options:options error:nil]; // 上下文对象设置属性为持久化存储器
_context.persistentStoreCoordinator = store; } //插入插入
- (void)insert
{
// 单表插入
// Person * model = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:_context];
// NSLog(@"--------mode:%@",model.class);
//
// model.age = arc4random()%20;
// model.name = @"lwq";
// model.address = @"bj";
// model.num = arc4random()&10; // 多表插入
Student * student = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:_context];
student.age = arc4random()%10;
student.name = @"jack"; Course *course = [NSEntityDescription insertNewObjectForEntityForName:@"Course" inManagedObjectContext:_context];
course.course_id = arc4random()%20;
course.course_name = @"英语";
// [student addStu_course:[NSSet setWithObject:course]];
student.stu_course = [NSSet setWithObject:course]; Classes *classes = [NSEntityDescription insertNewObjectForEntityForName:@"Classes" inManagedObjectContext:_context];
classes.class_name = [NSString stringWithFormat:@"高二(%u)班",arc4random()%3];
classes.class_id = arc4random()%10;
student.stu_classes = classes; NSError *error ;
if ([_context hasChanges]) {
[_context save:&error];
}
if (error) {
NSLog(@"插入数据失败");
}
NSLog(@"插入数据成功");
} // 查询
- (NSArray<Person *>*)query
{
// 多表查询
NSFetchRequest *requst1 = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
requst1.predicate = [NSPredicate predicateWithFormat:@"stu_classes.class_name=%@",@"高二(1)班"]; NSArray *res1 = [_context executeFetchRequest:requst1 error:nil];
[res1 enumerateObjectsUsingBlock:^(Student * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"Student:[name:%@,age:%hd]",obj.name,obj.age);
}]; // 单表查询
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
NSArray<Person *> *res = [_context executeFetchRequest:request error:nil];
[res enumerateObjectsUsingBlock:^(Person * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"%@",[LWCoreDataManager personString:obj]);
}];
return res;
} //删除操作
- (void)delete
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"age < 10"];
request.predicate = pred; NSArray *res = [_context executeFetchRequest:request error:nil];
[res enumerateObjectsUsingBlock:^(Person * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[_context deleteObject:obj];
}];
NSError *error;
if ([_context hasChanges]) {
[_context save:&error];
}
if (error) {
NSLog(@"删除数据失败");
}
NSLog(@"删除i数据成功");
} //更新操作
- (void)update
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"]; request.predicate = [NSPredicate predicateWithFormat:@"age >10"]; NSArray *res = [_context executeFetchRequest:request error:nil]; [res enumerateObjectsUsingBlock:^(Person* _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
obj.age = 12;
obj.name = @"rose";
obj.num = 100;
}];
NSError *error;
if ([_context hasChanges]) {
[_context save:&error];
}
if (error) {
NSLog(@"更新数据数据失败");
}
NSLog(@"更新数据成功");
} + (NSString *)personString:(Person *)p
{
return [NSString stringWithFormat:@"Person:[age:%hd,name:%@,address:%@,num:%hd]",p.age,p.name,p.address,p.num];
} @end
LWCoreDataManager.m
CoreData多线程的相关:
https://www.jianshu.com/p/283e67ba12a3
iOS CoreData总结的更多相关文章
- iOS CoreData技术学习资源汇总
一.CoreData学习指引 1. 苹果官方:Core Data Programming Guide 什么是CoreData? 创建托管对象模型 初始化Core Data堆栈 提取对象 创建和修改自定 ...
- IOS CoreData 多表查询demo解析
在IOS CoreData中,多表查询上相对来说,没有SQL直观,但CoreData的功能还是可以完成相关操作的. 下面使用CoreData进行关系数据库的表与表之间的关系演示.生成CoreData和 ...
- iOS CoreData (一) 增删改查
代码地址如下:http://www.demodashi.com/demo/11041.html Core Data是iOS5之后才出现的一个框架,本质上是对SQLite的一个封装,它提供了对象-关系映 ...
- iOS CoreData (二) 版本升级和数据库迁移
前言:最近ChinaDaily项目需要迭代一个新版本,在这个版本中CoreData数据库模型上有新增表.实体字段的增加,那么在用户覆盖安装程序时就必须要进行CoreData数据库的版本升级和旧数据迁移 ...
- IOS CoreData 多表查询(下)
http://blog.csdn.net/fengsh998/article/details/8123392 在iOS CoreData中,多表查询上相对来说,没有SQL直观,但COREDATA的功能 ...
- iOS CoreData 介绍和使用(以及一些注意事项)
iOS CoreData介绍和使用(以及一些注意事项) 最近花了一点时间整理了一下CoreData,对于经常使用SQLite的我来说,用这个真的有点用不惯,个人觉得实在是没发现什么亮点,不喜勿喷啊.不 ...
- iOS CoreData介绍和使用(以及一些注意事项)
iOS CoreData介绍和使用(以及一些注意事项) 最近花了一点时间整理了一下CoreData,对于经常使用SQLite的我来说,用这个真的有点用不惯,个人觉得实在是没发现什么亮点,不喜勿喷啊.不 ...
- iOS - CoreData 数据库存储
1.CoreData 数据库 CoreData 是 iOS SDK 里的一个很强大的框架,允许程序员以面向对象的方式储存和管理数据.使用 CoreData 框架,程序员可以很轻松有效地通过面向对象的接 ...
- iOS coreData问题
iOS常见错误-CoreData: Cannot load NSManagedObjectModel.nil is an illegal URL parameter 这是因为在工程中CoreData的 ...
- ios Coredata 的 rollback undo 等事物处理函数
首先说明 ios 中 NSManagedObjectContext 默认的 undoManager是nil的,就是说 undo 和 redo 都是没用的. 但是 rollback函数和reset函数是 ...
随机推荐
- SpringBoot 整合 JDBC 实例
0.数据库表 CREATE DATABASE springboot; USE springboot; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_ ...
- sql求每家店铺销量前三的sku, 附python解法
背景 有一张表: date store_id sku sales 2023-01-01 CK005 03045 50 date 代表交易日期,store_id代表门店编号,sku代表商品,sales代 ...
- sql计算众数及中位数
众数 众数: 情况①:一组数据中,出现次数最多的数就叫这组数据的众数. 举例:1,2,3,3,4的众数是3. 情况② :如果有两个或两个以上个数出现次数都是最多的,那么这几个数都是这组数据的众数. 举 ...
- Vulnhub Development Walkthrough
Vulnhub Development Walkthrough Recon 首先使用netdiscover进行二层Arp扫描. ┌──(kali㉿kali)-[~] └─$ sudo netdisco ...
- C# 从0到实战--程序入门:基本程序结构·hello,world
为什么要写博客 某人是一名大学生,到了大二,学院开始教授.Net,从这里我接触到了C#和ASP.Net,这些技术让我感到了想不到的快速开发之震撼.于是突发奇想,写此博客来记录我的学习路程.博客不仅仅是 ...
- ArrayList实现原理和自动扩容
ArrayList在Java集合中的位置, ArrayList原理: transient Object[] elementData; ArrayList通过数组来实现. 默认构造方法会构造一个容量为1 ...
- [人脸活体检测] 论文:Face De-Spoofing: Anti-Spoofing via Noise Modeling
Face De-Spoofing: Anti-Spoofing via Noise Modeling 论文简介 将非活体人脸图看成是加了噪声后失真的x,用残差的思路检测该噪声从而完成分类. 文章引用量 ...
- [OpenCV-Python] 8 用滑动条做调色板
文章目录 OpenCV-Python:II OpenCV 中的 Gui 特性 8 用滑动条做调色板 8.1 代码示例 练习 OpenCV-Python:II OpenCV 中的 Gui 特性 8 用滑 ...
- Centos7.x 安装 newman + postman
一.基础环境 输入 npm -v (查看 npm 版本) 输入 node -v(查看 node 版本) 二.安装newman 1.执行 npm install –g newman 进行安装 2.验证安 ...
- 分享一下.net core mvc的ModelStateExtend
主要代码: using Cracker.Core.Function; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace Cracker.Co ...