这次给大家带来的是CoreData多表操作的使用.

首先我们要对CoreData来进行多表操作我们先要创建至少两个实体在工程中。

在创建完成这两个对应的工程实体文件和工程中的类文件后我们现在需要创建一个整体的管理文件来管理这两个文件中的对应的model文件的添加删除和修改。一般我们创建的的管理文件大多都是单例类所以我们现在来创建一个类文件继承与NSObject名字叫做CoreDataManager。

创建完成后在内部添加学生和班级的添加删除和查询的方法,一般我们创建学生时要确定学生对应的班级所以添加学生的时候需要有对应班级的参数。而创建班级时我们只需要指定好班级名称就可以。以下是这些方法的内部实现

//使用GCD创建单例
+(CoreDataManager *)shareManager
{
static CoreDataManager *manager = nil;
static dispatch_once_t queue;
dispatch_once(&queue, ^{
manager = [[CoreDataManager alloc] init];
});
return manager;
} //添加班级
-(void)addClassEntity:(NSString *)string
{
//创建班级实体的描述
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"ClassEntity" inManagedObjectContext:[kAppdelegate managedObjectContext]];
//创建班级实体
ClassEntity *classEntity = [[ClassEntity alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:[kAppdelegate managedObjectContext]];
//给班级实体的属性命名
classEntity.name = string;
//循环创建班级中对应的学生
for (int i = 0; i < 10; i++) {
//调用学生的创建方法来创建学生实体
[classEntity addStudentEntityObject:[self addStudentWithString:@"张三" class:classEntity]];
}
//保存到真实地数据库中
[kAppdelegate saveContext];
} -(StudentEntity *)addStudentWithString:(NSString *)string class:(ClassEntity *)classEntity
{
//创建学生的实体描述
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"StudentEntity" inManagedObjectContext:[kAppdelegate managedObjectContext]];
//创建学生实体
StudentEntity *student = [[StudentEntity alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:[kAppdelegate managedObjectContext]];
//给学生的实体属性赋值
student.name = string;
//给到指定的班级中
student.classEntity = classEntity;
//保存到真实的数据库中
[kAppdelegate saveContext];
//返回创建的好的学生
return student;
} //查询班级
-(NSArray *)selectClassEntity
{
//创建查询请求
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"ClassEntity"];
//获取查询结果
NSArray *arr = [[kAppdelegate managedObjectContext] executeFetchRequest:fetchRequest error:nil];
//返回结果
return arr;
} //删除班级 -(void)deleteClassEntity
{
//获取当前所有的班级
NSArray *arr = [self selectClassEntity];
//循环遍历所有的班级并删除
for (ClassEntity *classEntity in arr) {
//实体删除方法
[[kAppdelegate managedObjectContext] deleteObject:classEntity];
}
//修改真实数据库
[kAppdelegate saveContext];
} - (void)modifyClassEntity
{
//通过查询语句获取当前所有的班级
NSArray *arr = [self selectClassEntity];
//forin遍历所有的班级
for (ClassEntity *classEntyity in arr) {
//修改所有班级的名称
classEntyity.name = @"BJS166666";
}
//保存当前的修改到真实数据库中
[kAppdelegate saveContext];
} //根据班级添加学生
-(void)addStudentWithClass:(ClassEntity *)classEntity
{
//创建学生实体描述
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"StudentEntity" inManagedObjectContext:[kAppdelegate managedObjectContext]];
//创建学生实体
StudentEntity *student = [[StudentEntity alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:[kAppdelegate managedObjectContext]];
//给学生实体属性赋值
student.name = @"李四";
//指定学生实体所属的班级
student.classEntity = classEntity;
//保存到真实数据库中
[kAppdelegate saveContext];
} //根据班级查询学生
- (NSMutableArray *)selectStudentEntityWithClassEntity:(ClassEntity *)classEntity
{
//创建可变数组来存放班级中存在的学生
NSMutableArray *arr = [NSMutableArray array];
//直接通过上级传入的班级获取班级中所有的学生
for (StudentEntity *student in classEntity.studentEntity) {
//在数组中添加学生实体
[arr addObject:student];
}
//添加完成后返回存放学生的数组
return arr;
} //根据班级删除学生
-(void)deleteStudentEntityWithClassEntity:(ClassEntity *)classEntity
{
//遍历当前班级下的所有学生
for (StudentEntity *studentEntity in classEntity.studentEntity) {
//删除当前班级下的学生
[[kAppdelegate managedObjectContext] deleteObject:studentEntity];
}
//修改真实数据库中的文件
[kAppdelegate saveContext];
}

  在这些文件内的方法都实现后我们就可以直接在你想要实现的控制器中去使用这些方法了

创建班级类然后在班级类的ViewDidLoad中创建添加删除和修改的按钮

- (void)viewDidLoad {
[super viewDidLoad]; // Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO; // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem; //创建添加班级的按钮
UIBarButtonItem *bar = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addClass)];
self.navigationItem.rightBarButtonItem = bar; //创建删除班级的按钮
UIBarButtonItem *bar1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(deleteClass)];
self.navigationItem.leftBarButtonItem = bar1;
//获取当前所有的班级
[self selectClassEntity];
//创建修改班级的按钮
UIButton *modifyButton = [UIButton buttonWithType:UIButtonTypeSystem];
[modifyButton addTarget:self action:@selector(modifyClass) forControlEvents:UIControlEventTouchUpInside];
[modifyButton setTitle:@"修改" forState:UIControlStateNormal];
self.navigationItem.titleView = modifyButton;
}

  然后再控制器中去实现对应的方法

//点击按钮添加班级
- (void)addClass
{
[[CoreDataManager shareManager] addClassEntity:[NSString stringWithFormat:@"BJS150%03d",arc4random()%100+1]];
[self selectClassEntity]; } //查询班级并刷新界面
-(void)selectClassEntity
{
self.classArr = [[CoreDataManager shareManager] selectClassEntity];
[self.tableView reloadData];
} //删除班级
- (void)deleteClass
{
[[CoreDataManager shareManager] deleteClassEntity];
[self selectClassEntity];
} //修改班级
- (void)modifyClass
{
[[CoreDataManager shareManager] modifyClassEntity];
[self selectClassEntity];
}

  在查询结束后使用查询完成后的结果

//
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
} - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.classArr.count;
} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
cell.textLabel.text = [self.classArr[indexPath.row] name];
// Configure the cell...
return cell;
}

在给每个cell赋完值后我们就可以实现班级界面向学生界面的跳转了

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
SecondTableViewController *secondVC = [SecondTableViewController new];
secondVC.studentArr = [NSMutableArray array];
//读取当前班级下的所有的学生并传到下级界面
for (StudentEntity *student in [self.classArr[indexPath.row] studentEntity]) {
[secondVC.studentArr addObject:student];
}
//将当前的班级整体传到下级界面等待下级界面的操作使用
secondVC.classEntity = self.classArr[indexPath.row];
[self.navigationController pushViewController:secondVC animated:YES];
}

  然后创建学生类的控制器并在ViewDidLoad中实现学生的增删改查

- (void)viewDidLoad {
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO; // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem; //创建添加学生的按钮
UIBarButtonItem *bar = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addStudent)];
self.navigationItem.rightBarButtonItem = bar;
//创建删除学生的按钮
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
[button setTitle:@"删除" forState:UIControlStateNormal];
[button addTarget:self action:@selector(deleteStudent) forControlEvents:UIControlEventTouchUpInside];
button.frame = CGRectMake(0, 0, 100, 30);
self.navigationItem.titleView = button; }

实现这些后实现每个按钮的点击事件

//添加学生
- (void)addStudent
{
[[CoreDataManager shareManager] addStudentWithClass:self.classEntity];
[self seleteStudentEntity];
}
//查询学生
- (void)seleteStudentEntity
{
self.studentArr = [[CoreDataManager shareManager] selectStudentEntityWithClassEntity:self.classEntity];
[self.tableView reloadData];
} //删除学生
- (void)deleteStudent
{
[[CoreDataManager shareManager] deleteStudentEntityWithClassEntity:self.classEntity];
[self seleteStudentEntity]; }

  在查询到学生的数据后给对应的cell赋值

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
} - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.studentArr.count;
} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"cell1";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
cell.textLabel.text = [self.studentArr[indexPath.row] name];
// Configure the cell... return cell;
}

  好的在做完这几部操作后咱们对多表CoreData的操作就完成了.

  

  

  

CoreData多表操作.的更多相关文章

  1. IOS CoreData 多表查询demo解析

    在IOS CoreData中,多表查询上相对来说,没有SQL直观,但CoreData的功能还是可以完成相关操作的. 下面使用CoreData进行关系数据库的表与表之间的关系演示.生成CoreData和 ...

  2. CoreData 多表 关联

    本文转载至 http://www.jianshu.com/p/e9f3b5e0cd19 1.概念简介 coreData中存在复杂的数据关系时,一张表难以满足需求,此时就需要了解使用coreData多表 ...

  3. Mysql常用表操作 | 单表查询

    160905 常用表操作 1. mysql -u root -p 回车 输入密码   2. 显示数据库列表 show databases     3. 进入某数据库 use database data ...

  4. Sql Server系列:数据表操作

    表是用来存储数据和操作数据的逻辑结构,用来组织和存储数据,关系数据库中的所有数据都表现为表的形式,数据表由行和列组成.SQL Server中的数据表分为临时表和永久表,临时表存储在tempdb系统数据 ...

  5. 学习MySQL之单表操作(二)

    ##单表操作 ##创建表 CREATE TABLE t_employee( empno ), ename ), job ), MGR ), Hiredate DATE DEFAULT '0000-00 ...

  6. python——Django(ORM连表操作)

    千呼万唤始出来~~~当当当,终于系统讲了django的ORM操作啦!!!这里记录的是django操作数据库表一对多.多对多的表创建及操作.对于操作,我们只记录连表相关的内容,介绍增加数据和查找数据,因 ...

  7. mysql数据表操作&库操作

    首先登陆mysql:mysql -uroot -proot -P3306 -h127.0.0.1 查看所有的库:show databases; 进入一个库:use database; 显示所在的库:s ...

  8. SQL server基础知识(表操作、数据约束、多表链接查询)

    SQL server基础知识 一.基础知识 (1).存储结构:数据库->表->数据 (2).管理数据库 增加:create database 数据库名称 删除:drop database ...

  9. Python之Django--ORM连表操作

    一对多 class UserType(models.Model): caption = models.CharField(max_length=32) class UserInfo(models.Mo ...

随机推荐

  1. python模拟Get请求保存网易歌曲的url

    python模拟Get请求保存网易歌曲的url 作者:vpoet mail:vpoet_sir@163.com 日期:大约在夏季 #coding:utf-8 import requests impor ...

  2. 【SDUT 3038】迷之博弈

    action=showproblem&problemid=3038">[SDUT 3038]迷之博弈 简直就是上次省赛的缩减版... 仅仅只是这个是链 省赛是环. ..1 2先 ...

  3. Java 线程第三版 第八章 Thread与Collection Class 读书笔记

        JDK1.2引入最有争议性的改变是将集合类默觉得不是Thread安全性的. 一.Collection Class的概述 1. 具有Threadsafe 的Collection Class: j ...

  4. ffmpeg学习笔记

           对于每一个刚開始学习的人,刚開始接触ffmpeg时,想必会有三个问题最为关心,即ffmpeg是什么?能干什么?怎么開始学习?本人前段时间開始接触ffmpeg,在刚開始学习过程中.这三个问 ...

  5. kaggle之电影评论文本情感分类

    电影文本情感分类 Github地址 Kaggle地址 这个任务主要是对电影评论文本进行情感分类,主要分为正面评论和负面评论,所以是一个二分类问题,二分类模型我们可以选取一些常见的模型比如贝叶斯.逻辑回 ...

  6. yum安装epel库后,安装软件总是提示Error: Cannot retrieve metalink for repository: epel. Please verify its path and try again(无法检索epel仓库)

    解决方法: vi /etc/yum.repos.d/epel.repo 将baseurl中的注释取消,将mirrorlist该列注释掉即可. 附图如下:

  7. win7使用右键导致死机、假死、explorer无法响应的解决方法

    右键引起explorer无法响应,奔溃,主要是由于COMCTL32.DLL和COMCTL21.OCX文件引起的 描述:comctl32.dll是Windows应用程序公用GUI图形用户界面模块.报告提 ...

  8. Git 分支管理详解

    大纲: 1.前言 2.创建分支 3.切换分支 4.合并分支(快速合并) 5.删除分支 6.分支合并冲突 7.合并分支(普通合并) 8.分支管理策略 9.团队多人开发协作 10.总结 注,测试机 Cen ...

  9. struts2框架的核心内容

     Struts1和Struts2的区别和对比: Action 类: • Struts1要求Action类继承一个抽象基类.Struts1的一个普遍问题是使用抽象类编程而不是接口,而struts2的Ac ...

  10. 踩坑学php(1)

    前言: 为什么要学php 呢?作为一个前端,一直有着了解后台的好奇心:作为一个计算机毕业的,一直有着实践更多设计模式和数据库相关的东西:而php 非常流行,拥有非常多的资源,入门应该容易: 为什么叫& ...