NSFetchedResultController与UITableView
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)
//初始化fetchedRC必须要排序
request.fetchBatchSize = 20;
NSSortDescriptor *priceSort = [NSSortDescriptor sortDescriptorWithKey:@"price" ascending:YES];
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
//如果要对上下文内容进行修改,可managedObjectContent存在于Appdelegate中,须通过协议进行引用。
NSFetchedResultController与UITableView的更多相关文章
- iOS UITableView 与 UITableViewController
很多应用都会在界面中使用某种列表控件:用户可以选中.删除或重新排列列表中的项目.这些控件其实都是UITableView 对象,可以用来显示一组对象,例如,用户地址薄中的一组人名.项目地址. UITab ...
- UITableView(二)
#import "ViewController.h" @interface ViewController () @end @implementation ViewControlle ...
- iOS: 在UIViewController 中添加Static UITableView
如果你直接在 UIViewController 中加入一个 UITableView 并将其 Content 属性设置为 Static Cells,此时 Xcode 会报错: Static table ...
- iOS 编辑UITableView(根据iOS编程编写)
上个项目我们完成了 JXHomepwner 简单的应用展示,项目地址.本节我们需要在上节项目基础上,增加一些响应用户操作.包括添加,删除和移动表格. 编辑模式 UITableView 有一个名为 e ...
- 使用Autolayout实现UITableView的Cell动态布局和高度动态改变
本文翻译自:stackoverflow 有人在stackoverflow上问了一个问题: 1 如何在UITableViewCell中使用Autolayout来实现Cell的内容和子视图自动计算行高,并 ...
- iOS - UITableView中Cell重用机制导致Cell内容出错的解决办法
"UITableView" iOS开发中重量级的控件之一;在日常开发中我们大多数会选择自定Cell来满足自己开发中的需求, 但是有些时候Cell也是可以不自定义的(比如某一个简单的 ...
- UITableView cell复用出错问题 页面滑动卡顿问题 & 各杂七杂八问题
UITableView 的cell 复用机制节省了内存,但是有时对于多变的自定义cell,重用时会出现界面出错(例如复用出错,出现cell混乱重影).滑动卡顿等问题,这里只简单敲下几点复用出错时的解决 ...
- UITableview delegate dataSource调用探究
UITableview是大家常用的UIKit组件之一,使用中我们最常遇到的就是对delegate和dataSource这两个委托的使用.我们大多数人可能知道当reloadData这个方法被调用时,de ...
- UITableView点击每个Cell,Cell的子内容的收放
关于点击TableviewCell的子内容收放问题,拿到它的第一个思路就是, 方法一: 运用UITableview本身的代理来处理相应的展开收起: 1.代理:- (void)tableView:(UI ...
随机推荐
- NoSQL-MongoDB with python
前言: MongoDB,文档存储型数据库(document store).NoSQL数据库中,它独占鳌头,碾压其他的NoSQL数据库. 使用C++开发的,性能仅次C.与redis一样,开源.高扩展.高 ...
- poj 3270(置换 循环)
经典的题目,主要还是考思维,之前在想的时候只想到了在一个循环中,每次都用最小的来交换,结果忽略了一种情况,还可以选所有数中最小的来交换一个循环. Cow Sorting Time Limit: 200 ...
- CSU-1632 Repeated Substrings[后缀数组求重复出现的子串数目]
评测地址:https://cn.vjudge.net/problem/CSU-1632 Description 求字符串中所有出现至少2次的子串个数 Input 第一行为一整数T(T<=10)表 ...
- 【BZOJ4444】[Scoi2015]国旗计划 双指针+倍增
[BZOJ4444][Scoi2015]国旗计划 Description A国正在开展一项伟大的计划——国旗计划.这项计划的内容是边防战士手举国旗环绕边境线奔袭一圈.这项计划需要多名边防战士以接力的形 ...
- MVC5学习系列
前言 嗷~小弟我又出现了~咳咳..嚎过头了, 先说一说为什么写这个吧,~首先肯定是我自己需要学(废话 - -,)//,之前也写过MVC4的项目,嗯..但是仅限于使用并没有很深入的每个模块去了解, 这段 ...
- android菜鸟学习笔记31----Android使用百度地图API(二)获取地理位置及地图控制器的简单使用
1.获取当前地理位置: Android中提供了一个LocationManager的类,用于管理地理位置.不能通过构造函数获取该类的实例,而是通过Context的getSystemService(): ...
- coursera 《现代操作系统》 -- 第十周 文件系统(2)
身份验证 Authentication 知道用户是谁.通过账号密码.Id 这样的识别出来. 访问控制 Permission 知道用户是谁后. 主动控制 记录用户ID和对应的访问权限 --> 记录 ...
- General Decimal Arithmetic 浮点算法
General Decimal Arithmetic http://speleotrove.com/decimal/ General Decimal Arithmetic [ FAQ | Decima ...
- php-fpm 启动 关闭 进程逃逸 pid
正常关闭失败 [root@d personas]# /etc/init.d/php-fpm stopGracefully shutting down php-fpm /etc/init.d/php-f ...
- bat masterNodeRun.bat
C:\> compare C:\> compare C:\>D:\cmd\wphp.bat C:\> compareReq -- :: TODO StartScript -- ...