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. SGU 208. Toral Tickets

    208. Toral Tickets time limit per test: 0.25 sec. memory limit per test: 65536 KB input: standard ou ...

  2. vue 分页插件

    有个小问题就是最多显示3个分页,可以手动改一下配置参数就好.直接代码: <template> <div class="pageination_align"> ...

  3. run-time setting 中设置simulate browser cache 选项详解

    Browser  Emulation: Simulate  browser  cache:配置Vuser模拟带缓存的浏览器.缺省缓存是被允许的, 可以通过禁止该选项来使得所有VUser模拟的浏览器都不 ...

  4. IDA问题相关

    1.当想使用F5时出现“please position the cursor within a function”,那么就创建函数,但是创建时出现“The function has undefined ...

  5. PHP获取以为数组中的最大值和最小值

    1.PHP获取一维数组中的最大值 <?php $a=array('1','3','55','99'); $pos = array_search(max($a), $a); echo $a[$po ...

  6. python3 怎么爬取新闻网站?

    先开个坑,以后再填吧....... import requests from bs4 import BeautifulSoup def content(url): text = requests.ge ...

  7. Jquery操作select标签的常用方法

    <select id="search"> <option value='1'>baidu</option> <option value=' ...

  8. 同等条件下,mongo为什么比mysql快?

    写操作MongoDB比传统数据库快的根本原因是Mongo使用的内存映射技术 - 写入数据时候只要在内存里完成就可以返回给应用程序,这样并发量自然就很高.而保存到硬体的操作则在后台异步完成. 读操作Mo ...

  9. asp.net core集成CAP(分布式事务总线)

    一.前言 感谢杨晓东大佬为社区贡献的CAP开源项目,传送门在此:.NET Core 事件总线,分布式事务解决方案:CAP 以及 如何在你的项目中集成 CAP[手把手视频教程],之前也在工作中遇到分布式 ...

  10. File Associations