CoreData数据库是用来持久性存储数据的,那么,我们再从该数据库中取出数据干什么呢?明显的是为了对数据做操作,这个过程中可以将它们直观的显示出来,即通过表格的形式显示出来。CoreData配合tableView一起使用,是很常用的一种方式,直观、清晰明了。

下面就来具体的举个例子:

要求:将数据库中的数据显示在表格中,并且可以进行删除、插入等一些操作。

前期的具体步骤:

1、创建项目时,勾选Use Core Data,生成CoreData_____.xcdatamodel文件;

2、点击CoreData_____.xcdatamodel文件,进入项目面板,点击左下角的Add Entity创建实体对象;

    

3、在Attributes处点击'+'号,添加实体对象的属性

4、选中实体对象,点击模拟器菜单栏上的Editor下的create NSManagedObjectSubclass..,自动创建该实体对象的类

        

5、点击项目面板右下角的style查看所创建的表

6、在故事板Storyboard中拖入一个表格UITableView,并将tableView和控制类进行IBOutlet关联

好了,在AppDelegate和Student类编译器自动帮助声明和定义了需要的方法和属性,前期的工作已经完成,最后就是代码来操作数据库了:

在AppDelegate类中准备测试数据并将它们存储到数据库中:

 #import "AppDelegate.h"
#import "Student.h" @interface AppDelegate ()
@property (assign,nonatomic)BOOL isInserted;
@end @implementation AppDelegate //准备测试数据
-(void)addStudentWithName:(NSString *)name andAge:(NSNumber*)age andGender:(NSNumber*)gender
{
//取数据库中实体对象
Student *student = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([Student class]) inManagedObjectContext:self.managedObjectContext]; student.name = name;
student.age = age;
student.gender = gender;
} - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //在偏好设置中设置标识符,用来防止数据被重复插入
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
self.isInserted = [userDefaults boolForKey:@"isInserted"]; //设置实体对象的属性
if(!self.isInserted)
{
[self addStudentWithName:@"张三" andAge:@ andGender:@'M'];
[self addStudentWithName:@"李四" andAge:@ andGender:@'F'];
[self addStudentWithName:@"王五" andAge:@ andGender:@'M'];
[self addStudentWithName:@"赵六" andAge:@ andGender:@'F'];
[self addStudentWithName:@"陈七" andAge:@ andGender:@'F'];
[self addStudentWithName:@"郑八" andAge:@ andGender:@'M'];
[self addStudentWithName:@"戴九" andAge:@ andGender:@'M'];
[self addStudentWithName:@"刘十" andAge:@ andGender:@'F'];
} //设置偏好设置,并强制写到文件中
[userDefaults setBool:YES forKey:@"isInserted"];
[userDefaults synchronize]; //保存数据到持久层
[self saveContext]; return YES;
}

在控制器类ViewController中取出数据库中的数据,并将它们显示在表格中,然后进行删除和插入操作:

 #import "ViewController.h"
#import "AppDelegate.h"
#import "Student.h" @interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong,nonatomic)NSMutableArray *stus;
@end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
//设置应用程序代理
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate]; //设置数据源和代理
self.tableView.dataSource = self;
self.tableView.delegate = self; //从CoreData数据库中取出实体对象信息 //创建请求对象
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass([Student class])]; //批处理
fetchRequest.fetchBatchSize = 10; //创建排序对象
NSSortDescriptor *ageSort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
[fetchRequest setSortDescriptors:@[ageSort]]; //上下文发送查询请求
NSError *error = nil;
NSArray *array = [appDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if(error)
{
return; //获取数据失败
} self.stus = [NSMutableArray arrayWithArray:array]; } //设置行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.stus.count;
}
//设置每一个单元格的内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//1.根据reuseIdentifier,先到对象池中去找重用的单元格对象
static NSString *reuseIdentifier = @"stuCell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
//2.如果没有找到,自己创建单元格对象
if(cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
}
//3.设置单元格对象的内容
Student *student = [self.stus objectAtIndex:indexPath.row];
cell.textLabel.text = student.name;
cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ %c",student.age,(char)[student.gender integerValue]];
return cell;
} //编辑单元格
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
} //编辑类型
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
//删除
return UITableViewCellEditingStyleDelete;
} //对编辑类型的处理
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{ AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate]; //删除CoreData数据库中数据
Student *student = [self.stus objectAtIndex:indexPath.row];
[appDelegate.managedObjectContext deleteObject:student];
NSError *error = nil;
[appDelegate.managedObjectContext save:&error];
if(error)
{
NSLog(@"删除失败");
} //删除数据源数据
[self.stus removeObjectAtIndex:indexPath.row]; //删除一条记录的同时,往CoreData数据库插入两条数据
[appDelegate addStudentWithName:@"小明" andAge:@ andGender:@'M'];
[appDelegate addStudentWithName:@"小李" andAge:@ andGender:@'M']; [appDelegate.managedObjectContext save:&error];
if(error)
{
NSLog(@"删除失败");
}

        //局部刷新表格

          //[self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];

     //整体刷新表格
[self.tableView reloadData];
} @end

演示结果如下:

从数据库取出数据显示在表格上                         在单元格上从左向右滑动删除数据

          

删除几个数据后显示结果                 删除一次时,(重新取数据仅仅删除了郑八时)同时插入两个指定的数据后结果

          

iOS:CoreData数据库的使用三(数据库和tableView表格一起使用)的更多相关文章

  1. QF——iOS中的数据库操作:SQLite数据库,第三方封装库FMDB,CoreData

    SQLite数据库: SQLite是轻量级的数据库,适合应用在移动设备和小型设备上,它的优点是轻量,可移植性强.但它的缺点是它的API是用C写的,不是面向对象的.整体来说,操作起来比较麻烦.所以,一般 ...

  2. iOS CoreData (二) 版本升级和数据库迁移

    前言:最近ChinaDaily项目需要迭代一个新版本,在这个版本中CoreData数据库模型上有新增表.实体字段的增加,那么在用户覆盖安装程序时就必须要进行CoreData数据库的版本升级和旧数据迁移 ...

  3. 使用iOS原生sqlite3框架对sqlite数据库进行操作

    摘要: iOS中sqlite3框架可以很好的对sqlite数据库进行支持,通过面向对象的封装,可以更易于开发者使用. 使用iOS原生sqlite3框架对sqlite数据库进行操作 一.引言 sqlit ...

  4. iOS学习36数据处理之SQLite数据库

    1. 数据库管理系统 1> SQL语言概述 SQL: SQL是Structured Query Language(结构化查询语言)的缩写.SQL是专为数据库而建立的操作命令集, 是一种功能齐全的 ...

  5. GZFramwork数据库层《三》普通主从表增删改查

    运行结果: 使用代码生成器(GZCodeGenerate)生成tb_Cusomer和tb_CusomerDetail的Model 生成器源代码下载地址: https://github.com/Gars ...

  6. SQL数据库基础(三)

    认识数据库备份和事务日志备份 数据库备份与日志备份是数据库维护的日常工作,备份的目的是在于当数据库出现故障或者遭到破坏时可以根据备份的数据库及事务日志文件还原到最近的时间点将损失降到最低点. 数据库备 ...

  7. [置顶] VB6基本数据库应用(三):连接数据库与SQL语句的Select语句初步

    同系列的第三篇,上一篇在:http://blog.csdn.net/jiluoxingren/article/details/9455721 连接数据库与SQL语句的Select语句初步 ”前文再续, ...

  8. python对mysql数据库操作的三种不同方式

    首先要说一下,在这个暑期如果没有什么特殊情况,我打算用python尝试写一个考试系统,希望能在下学期的python课程实际使用,并且尽量在此之前把用到的相关技术都以分篇博客的方式分享出来,有想要交流的 ...

  9. mysql数据库连接池使用(三)数据库元数据信息反射数据库获取数据库信息

    1.1. mysql数据库连接池使用(三)数据库元数据信息反射数据库获取数据库信息 有时候我们想要获取到数据库的基本信息,当前程序连接的那个数据库,数据库的版本信息,数据库中有哪些表,表中都有什么字段 ...

随机推荐

  1. easyui layout 左右面板折叠后 显示标题

    (function($){ var buttonDir = {north:'down',south:'up',east:'left',west:'right'};    $.extend($.fn.l ...

  2. java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES) 解决办法

    一.背景 在Spark中,将DStream写入到MySQL出现错误:java.sql.SQLException: Access denied for user 'root'@'localhost' ( ...

  3. vscode 解决vue emmet不起作用

    现在 vscode 自带的提示已经很好用了,大部分时间自带的提示展示的 emmet 内容已经是所需的了 在首选项 设置中配置 v1.15.1 之后需要这样设置: "emmet.trigger ...

  4. Java 继承内部类

    大家有没有想过内部类究竟能不能被继承呢? public class Main { public static void main(String[] args){ Outer outer = new O ...

  5. db2部署与数据仓库应用

    概念特性 安装 基础命令 连接 监控 存储过程 数据合并 Merge Into是增量备份 结果集分组 row_number() OVER (PARTITION BY COL1 ORDER BY COL ...

  6. TCP的那些事-2

    这篇文章是下篇,所以如果你对TCP不熟悉的话,还请你先看看上篇<TCP的那些事儿(上)> 上篇中,我们介绍了TCP的协议头.状态机.数据重传中的东西.但是TCP要解决一个很大的事,那就是要 ...

  7. 导航控制器(UINavigationController)

    导航控制器管理一系列显示层次型信息的场景.它创建一个视图管理器"栈",栈底为根视图控制器,用户在场景间切换时,依次将试图控制器压入栈中,且当前场景的试图控制器位于栈顶.要返回上一级 ...

  8. go语言学习框架

    根据框架学习 https://books.studygolang.com/gopl-zh/ 看电子书 http://shinley.com/index.html

  9. HDU 6166 Spfa

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6166 题意:给出一个n个点的有向图.然后给你k个点,求这k个点任意两点之间的最短路的最小值.思路: 以 ...

  10. 【BZOJ 2007】 2007: [Noi2010]海拔 (平面图转对偶图+spfa)

    2007: [Noi2010]海拔 Time Limit: 20 Sec  Memory Limit: 552 MBSubmit: 2504  Solved: 1195 Description YT市 ...