1 #import "AppDelegate.h"
#import "Book.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
-(void)addBookWithTitle:(NSString *)title andAuthor:(NSString *)author andPrice:(NSNumber *)price
{
Book *book = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([Book class]) inManagedObjectContext:self.managedObjectContext];
book.title = title;
book.author = author;
book.price = price;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//如果不想每次执行时测试数据都重新插入一遍,可以使用偏好设置,如果已经存在了,就不再进行插入了。
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
BOOL isInserted = [userDefaults boolForKey:@"inInserted"];
if (!isInserted)
{
//插入数据
[self addBookWithTitle:@"*文*" andAuthor:@"徐" andPrice:@10000.1];
[self addBookWithTitle:@"西游记" andAuthor:@"吴承恩" andPrice:@20.5];
[self addBookWithTitle:@"水浒传" andAuthor:@"施耐庵" andPrice:@5.1];
[self addBookWithTitle:@"三国演义" andAuthor:@"罗贯中" andPrice:@10.2];
[self addBookWithTitle:@"史记" andAuthor:@"司马迁" andPrice:@45.3];
[self addBookWithTitle:@"资治通鉴" andAuthor:@"司马光" andPrice:@56.5];
[self saveContext];
//保存偏好设置
[userDefaults setBool:YES forKey:@"inInserted"];
//自动步更新
[userDefaults synchronize];
}
return YES;
}
 #import "BookTableViewController.h"
#import "Book.h"
#import "AppDelegate.h"
@interface BookTableViewController ()<NSFetchedResultsControllerDelegate>
@property(strong,nonatomic)NSFetchedResultsController *fetchedRC;
@property(strong,nonatomic)NSManagedObjectContext *managedObjectContext;
@end @implementation BookTableViewController - (void)viewDidLoad {
[super viewDidLoad];
//获取应用代理
AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
//本次案例需要对CoreData的内容进行修改,涉及到managedObjectContext,但是magagedObjetContext属于Appdelegate的属性,此处使用协议获取创建新的managedObjectContext;
self.managedObjectContext = delegate.managedObjectContext;
//使用fetchedRC获取数据
NSError *error = nil;
[self.fetchedRC performFetch:&error];
if (error) {
NSLog(@"NSFetchedResultsController获取数据失败");
}
}
-(NSFetchedResultsController *)fetchedRC
{
//判断fetchRC是否存在,如果不存在则创建新的,否则直接返回
if (!_fetchedRC) {
//使用NSFetchRequest进行获取数据
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass([Book class])];
request.fetchBatchSize = ;
//设置以某个字段进行排序,此案例以:price价格大小进行排序
NSSortDescriptor *priceSort = [NSSortDescriptor sortDescriptorWithKey:@"price" ascending:YES];
//对获取的数据进行排序
[request setSortDescriptors:@[priceSort]];
//创建新的fetchedRC
_fetchedRC = [[NSFetchedResultsController alloc]initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
_fetchedRC.delegate = self;
}
return _fetchedRC;
} #pragma mark - Table view data source
//设置tableView的分组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//分组的数据取决于创建sectionNameKeyPath的设置;
return self.fetchedRC.sections.count;
}
//设置tableView每组有多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
id sectionsInfo = [self.fetchedRC.sections objectAtIndex:section];
return [sectionsInfo numberOfObjects];
}
//自定义方法,设置单元格的显示内容
-(void)configCell:(UITableViewCell *)cell andIndexPath:(NSIndexPath *)indexPath
{
//获取选中的对象
Book *book = [self.fetchedRC objectAtIndexPath:indexPath];
cell.textLabel.text = [NSString stringWithFormat:@"%@ %@",book.title,book.author];
cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",book.price];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//1.根据reuseindentifier先到对象池中去找重用的单元格
static NSString *reuseIndetifier = @"bookCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIndetifier];
//2.如果没有找到需要自己创建单元格对象
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIndetifier];
}
//3.设置单元格对象的内容
[self configCell:cell andIndexPath:indexPath];
return cell;
}
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete)
{
Book *book = [self.fetchedRC objectAtIndexPath:indexPath];
//1.先删除CoreData中的相应数据
[self.managedObjectContext deleteObject:book];
//插入新的记录
AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
[delegate addBookWithTitle:@"唐诗三百首" andAuthor:@"李白等" andPrice:@12.3];
book.price = @([book.price doubleValue]+);
NSError *error = nil;
[self.managedObjectContext save:&error];
if(error) {
NSLog(@"失败");
}
} else if (editingStyle == UITableViewCellEditingStyleInsert)
{
}
}
#pragma mark - NSFetchedResultsController代理方法
-(void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView beginUpdates];
}
-(void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView endUpdates];
}
/**
* 以下方法共进行了两项操作:
1.判断操作的类型
2.对修改的数据、或新插入的数据位置进行局部刷新
*/
-(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)//更新操作
{
//首先获取cell;
UITableViewCell *cell = [self.fetchedRC objectAtIndexPath:indexPath];
//调用configCell方法
[self configCell:cell andIndexPath:indexPath];
//重新加载指定行
[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
@end
运行结果,如下图:
创建控制器

一般来说,你会创建一个NSFetchedResultsController实例作为tableview的成员变量。初始化的时候,你提供四个参数:

1。 一个fetchrequest.必须包含一个sortdescriptor用来给结果集排序。

2。 一个managedobject context。 控制器用这个context来执行取数据的请求。

3。 一个可选的keypath作为sectionname。控制器用keypath来把结果集拆分成各个section。(传nil代表只有一个section)

4。 一个cachefile的名字,用来缓冲数据,生成section和索引信息。
 
案例中:代码解析
使用fethedRequestController控制器获取数据,此处使用懒加载的方式读取数据:
_fetchedRC = [[NSFetchedResultsController alloc]initWithFetchRequest:request managedObjectContext:self.managedObjectContent sectionNameKeyPath:nil cacheName:@"book"];
参数解析:
参数1 :使用之前需通过NSFetchRequest进行读取数据,然后对request进行排序操作(必须排序你懂不?不排序就出错)。
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass([Book class])];
        //初始化fetchedRC必须要排序
        request.fetchBatchSize = 20;
        NSSortDescriptor *priceSort = [NSSortDescriptor sortDescriptorWithKey:@"price" ascending:YES];
        [request setSortDescriptors:@[priceSort]];
参数2:由于managedObjectContent是在Applelegate.h文件中,如果想要使用,需通过Application协议创建新的managedObjectContent。
//获取应用程序代理
    AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
    //如果要对上下文内容进行修改,可managedObjectContent存在于Appdelegate中,须通过协议进行引用。
    self.managedObjectContent = appDelegate.managedObjectContext;
参数3:在tableView中如果不准备进行分组显示,可以将值设为:nil;
参数4:设置缓存。
 

NSFetchedResultController与UITableView的更多相关文章

  1. iOS UITableView 与 UITableViewController

    很多应用都会在界面中使用某种列表控件:用户可以选中.删除或重新排列列表中的项目.这些控件其实都是UITableView 对象,可以用来显示一组对象,例如,用户地址薄中的一组人名.项目地址. UITab ...

  2. UITableView(二)

    #import "ViewController.h" @interface ViewController () @end @implementation ViewControlle ...

  3. iOS: 在UIViewController 中添加Static UITableView

    如果你直接在 UIViewController 中加入一个 UITableView 并将其 Content 属性设置为 Static Cells,此时 Xcode 会报错: Static table ...

  4. iOS 编辑UITableView(根据iOS编程编写)

    上个项目我们完成了 JXHomepwner 简单的应用展示,项目地址.本节我们需要在上节项目基础上,增加一些响应用户操作.包括添加,删除和移动表格. 编辑模式 UITableView 有一个名为  e ...

  5. 使用Autolayout实现UITableView的Cell动态布局和高度动态改变

    本文翻译自:stackoverflow 有人在stackoverflow上问了一个问题: 1 如何在UITableViewCell中使用Autolayout来实现Cell的内容和子视图自动计算行高,并 ...

  6. iOS - UITableView中Cell重用机制导致Cell内容出错的解决办法

    "UITableView" iOS开发中重量级的控件之一;在日常开发中我们大多数会选择自定Cell来满足自己开发中的需求, 但是有些时候Cell也是可以不自定义的(比如某一个简单的 ...

  7. UITableView cell复用出错问题 页面滑动卡顿问题 & 各杂七杂八问题

    UITableView 的cell 复用机制节省了内存,但是有时对于多变的自定义cell,重用时会出现界面出错(例如复用出错,出现cell混乱重影).滑动卡顿等问题,这里只简单敲下几点复用出错时的解决 ...

  8. UITableview delegate dataSource调用探究

    UITableview是大家常用的UIKit组件之一,使用中我们最常遇到的就是对delegate和dataSource这两个委托的使用.我们大多数人可能知道当reloadData这个方法被调用时,de ...

  9. UITableView点击每个Cell,Cell的子内容的收放

    关于点击TableviewCell的子内容收放问题,拿到它的第一个思路就是, 方法一: 运用UITableview本身的代理来处理相应的展开收起: 1.代理:- (void)tableView:(UI ...

随机推荐

  1. BestCoder Round #93 ABC

    A: 题目大意: 将数组划分成最少的段,每段的数两两不同. 题解:直接用一个map记录一个数是否出现过,贪心的每次取最多个数就好. B: 题目大意: 给出一个0-9组成的字符串,问能否删掉K个数字,使 ...

  2. asp.net中TextBox只能输入数字的最简洁的两种方法

    如下TextBox <asp:textboxonkeypress="isnum()"id="TextBox1"runat="server&quo ...

  3. Eigen求矩阵行列式 及 行列式本质

    转置.伴随.行列式.逆矩阵 小矩阵(4 * 4及以下)eigen会自动优化,默认采用LU分解,效率不高 #include <iostream> #include <Eigen/Den ...

  4. Python_Selenium之鼠标右键

    Python_Selenium之鼠标右键 一.步骤: (以百度为例)获取百度网址 找到需要右键的元素(定位),xpath表达式为“//*[@id='lg']/img” 然后,右键选择“在新标签页中打开 ...

  5. OpenCV学习笔记:opencv_core模块

    一,简介: opencv最基础的库.包含exception,point,rect,size,slice,vector,matrix,image等数据结构,和相应的操作函数,以及一些基础算法. 二,分析 ...

  6. day14 生成器的进阶

    一.生成器的两种形式  1.生成器函数的应用 # def cloth(): # for i in range(100): # yield '衣服%s'%i # # g = cloth() # for ...

  7. android菜鸟学习笔记29----Android应用向用户发送提示信息的方式总结

    常见的向用户发送提示信息的方式有3种,分别为: 1)发送Toast信息 2)弹出对话框 3)发送通知 总结如下: 方式1:发送Toast信息: 这种方式最简单,在之前的学习中多次使用过.Toast是在 ...

  8. 一个有趣的IP不同的问题?

    1.我们已经知道了内网和外网的显示是不同的. 2.今天发现了我的飞Q传输上显示的ip和电脑上网络中显示的ip不同,但是传输文件是可以的,至于这个问题目前没有找到合理的解释,解释这个问题,但是这样就奇怪 ...

  9. C#实体类序列化为XML

    这两天,应要求做一个C/S的小程序,考虑到程序简洁小巧,存数据的方式不使用数据库,而是直接存入XML文档中保存.为了把复杂实体类里面的属性存入XML,我们可以使用C#有的反射机制,做一个简单的通用工具 ...

  10. MySQL中事务的分类

    从事务理论的角度来看,可以把事务分为以下几种类型 扁平事务(Flat Transactions) 带有保存点的扁平事务(Flat Transactions with Savepoints) 链事务(C ...