CoreData数据库虽然可以和tableview或者UITableViewController一起使用将数据显示在表格上,但是在准备数据的时候,这种方式需要用一个可变数组来装从数据库一次性取出来的所有数据,然后通过操作这个数组来显示数据再表格上,从内存的优化和性能上来说并不是很好;这里,介绍一种新的抓取数据的方式,苹果公司为了进一步优化内存,创建了一个从数据库抓取数据的控制器NSFetchedResultsController,它能从CoreData中一批一批的抓取数据并存放起来,然后通过操作它来将数据显示在表格中,极大的优化了内存;与此同时,这个控制器还提供了一个<NSFetchedResultsControllerDelegate>协议,通过该控制器的代理可以实现数据的实时动画更新(删除、插入、修改)。CoreData数据库和UITableViewController以及NSFetchedResultsController一起使用,具有很强大的功能,是一个很不错的方式,推荐掌握这门技术。以下就具体的例子来介绍:

要求:创建一个实体对象Book数据库表,多次设置它的属性,并将它显示在表格中,显示后进行的操作有:(1)仅仅进行删除对象、(2)在删除时同时又插入两条对象信息、(3)删除时修改它的属性并再从新显示该对象

前期的创建数据库表的具体步骤:

1、创建新项目时,勾选Use Core Data,生成CoreData____NSFetchResultController.xcdatamodel文件,此时AppDelegate类中自动封装了sqlite的大量方法和需要的managedObjectContext、managedObjectModel、persistentStoreCoordinator三个对象等;

     

2、点击该文件,进入设置面板,点击左下角的Add Entity,创建实体对象并设置它的类名,同时在Attribute处添加该实体对象的属性;

      

3、选中该实体对象,点击模拟器菜单栏的Editor下的create NSManagedObjectSubclass..,自动生成实体对象的类Book.h和Book.m文件,类中自动生成了实体对象的所有属性;

         

4、再一次进入设置面板,点击右下角的style,可以查看成功创建的数据库表。

     

5、进入故事板Storyboard中,删除viewController控制器和它的类,重新拖入一个新的视图控制器和一个表格视图TableView;

6、新建一个新的类为BookTableViewController继承自UITableViewController,并将上面新拖入的视图控制器关联这个类即可。好了,前期工作完成。

                 

接下来即时具体的代码操作了:

在AppDelegate类的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法中奖数据存储到数据库:

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

     //读取偏好设置,使测试数据只插入一次
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
self.isInserted = [userDefaults boolForKey:@"isInserted"]; if(!self.isInserted)
{
[self addBookWithTitle:@"《红楼梦》" andPrice:@50.5];
[self addBookWithTitle:@"《西游记》" andPrice:@48.5];
[self addBookWithTitle:@"《水浒传》" andPrice:@67.5];
[self addBookWithTitle:@"《三国演义》" andPrice:@70.0];
[self addBookWithTitle:@"《资治通鉴》" andPrice:@79.0];
[self addBookWithTitle:@"《本草纲目》" andPrice:@59.0];
[self addBookWithTitle:@"《二十四史》" andPrice:@98.0]; } //设置偏好设置
[userDefaults setBool:YES forKey:@"isInserted"];
[userDefaults synchronize]; return YES;
}

//将设置上面对象属性的方法封装起来

 -(void)addBookWithTitle:(NSString*)title andPrice:(NSNumber*)price
{
//取出实体对象
Book *book = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([Book class]) inManagedObjectContext:self.managedObjectContext]; //设置属性
book.title = title;
book.price = price; //保存数据到持久层
[self saveContext]; }

在BookTableViewController.m文件中:

//导入头文件,实现协议和定义属性

 #import "BookTableViewController.h"
#import "AppDelegate.h"
#import "Book.h" @interface BookTableViewController ()<NSFetchedResultsControllerDelegate>
@property (strong,nonatomic)NSFetchedResultsController *fetchResultVC;
@property (strong,nonatomic)NSManagedObjectContext *managedObjectContext;

//NSFetchedResultsController从数据库抓取数据

 - (void)viewDidLoad {
[super viewDidLoad]; //创建应用程序对象
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate]; self.managedObjectContext = appDelegate.managedObjectContext; //fetchResultVC获取CoreData中的数据
NSError *error = nil;
[self.fetchResultVC performFetch:&error];
if(error)
{
NSLog(@"获取数据失败");
} }
//懒加载创建NSFecthedResultsController控制器对象
 -(NSFetchedResultsController*)fetchResultVC
{
if(!_fetchResultVC)
{
//创建请求对象
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass([Book class])]; //批处理,每次从数据库中抓取的数量
fetchRequest.fetchBatchSize = ; //设置排序对象
NSSortDescriptor *priceSort = [NSSortDescriptor sortDescriptorWithKey:@"price" ascending:YES];
[fetchRequest setSortDescriptors:@[priceSort]]; //创建fetchResultVC
_fetchResultVC = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"book"]; //设置fetchResultVC的代理
_fetchResultVC.delegate = self;
}
return _fetchResultVC;
}

#pragma mark - Table view data source//显示表格内容

//组数

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.fetchResultVC.sections.count;
}

//行数

 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
id<NSFetchedResultsSectionInfo> sectionInfo = [self.fetchResultVC.sections objectAtIndex:section]; return [sectionInfo numberOfObjects];
}

//将设置行内容的方法封装,调用它设置cell内容

 -(void)configCell:(UITableViewCell*)cell indexPath:(NSIndexPath*)indexPath
{
Book *book = [self.fetchResultVC objectAtIndexPath:indexPath];
cell.textLabel.text = book.title;
cell.detailTextLabel.text = [NSString stringWithFormat:@"$%@",book.price];
}
 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//1.根据reuseIdentifier,先到对象池中去找重用的单元格对象
static NSString *reuseIdentifier = @"bookCell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
//2.如果没有找到,自己创建单元格对象
if(cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
}
//3.设置单元格对象的内容
[self configCell:cell indexPath:indexPath];
return cell;
}

//设置单元格的编辑与否

 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}

//只进行删除数据

  Book *book = [self.fetchResultVC objectAtIndexPath:indexPath];//获取实体对象
NSError *error = nil; //删除数据
//从CoreData数据库删除数据
[self.managedObjectContext deleteObject:book];//从上下文是删除该实体对象
[self.managedObjectContext save:&error];//保存上下文

//删除数据时,同时新插入插入数据

   AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
[appDelegate addBookWithTitle:@"《狂人日记》" andPrice:@20.0];
[appDelegate addBookWithTitle:@"《洗冤集录》" andPrice:@24.5];

//删除数据时,修改数据并显示

 //在删除数据时,修改它的数据并更新
book.price = @([book.price doubleValue] + );
[self.managedObjectContext save:&error];
if(error)
{
NSLog(@"删除失败");
}

#pragma mark -<NSFetchedResultsControllerDelegate>代理方法,更新变化后的表格信息

 //表格开始更新
-(void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView beginUpdates];
}
//尽心更新处理
-(void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath
{
if(type == NSFetchedResultsChangeDelete) //删除数据
{
[self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
else if(type == NSFetchedResultsChangeInsert) //插入数据
{
[self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
else if(type == NSFetchedResultsChangeUpdate) //更新(修改)数据
{ UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
[self configCell:cell indexPath:indexPath]; [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
//表格更新结束
-(void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView endUpdates];
}

演示结果如下:

没有进行任何操作时:                       选中单元格往左滑动,删除数据时

        

删除数据时,同时新插入两个对象                        没删除一次,对象的属性价格就发生了改变

          

 

最新文章

  1. Oracle第一步
  2. SSH整合
  3. Objective - C NSArray不可变数组和NSMutableArray可变数组
  4. (转)Java动态代理与CGLib代理
  5. Error:(12) No resource identifier found for attribute &#39;titles&#39; in package &#39;com.itheima52.mobilesafe5
  6. JDK和Jython安装
  7. 转载:css3 box-shadow投影发光效果
  8. HDU1029时钟(排序)
  9. 判断程序是否在VMWare内运行
  10. CSS:重量和级联规则,确定其优先级
  11. 基于Predictive Parsing的ABNF语法分析器(十三)——rulelist、rule、rulename、define-as和elements
  12. css3技巧属性之text-overflow
  13. keil应用小贴士:Use MicroLIB是干什么的
  14. ELK学习记录一 :初识ELK
  15. struts2 easyui实现datagrid的crud
  16. 2019最新整理PHP面试题附答案
  17. xftp和xshell有什么区别
  18. url override and HttpSession implements session for real
  19. 编译安装php时遇到virtual memory exhausted: Cannot allocate memory
  20. Mac OS X下的移动光标和文字编辑快捷键

热门文章

  1. day4递归原理及实现
  2. Java String、StringBuilder和StringBuffer
  3. thinkphp5.0动态配置
  4. CodeForces 772A Voltage Keepsake
  5. 非洲top10人口大国2017年的人口、预期寿命、三大主粮进口量、92/08/17年的饥饿指数
  6. 在 HTTP Request 中加入特定的 Header
  7. Number 和 parseInt 区别
  8. CF1051D Bicolorings dp
  9. POJ 2728 JZYZOJ 1636 分数规划 最小生成树 二分 prim
  10. POJ2222 Keywords Search AC自动机模板