NSFetchedResultsController、CoreData、UITableView

// 1. 实体

@interface User : NSManagedObject

@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * phone;

@end


// 2. ViewController
直接上代码
#import "ViewController.h"
#import <CoreData/CoreData.h>
#import "User.h"
#import "AppDelegate.h"

@interface ViewController () <UITableViewDelegate,UITableViewDataSource ,NSFetchedResultsControllerDelegate>
// fetch 获取  result结果  controller 控制器
@property (nonatomic, strong) NSFetchedResultsController *fetchedResultsController;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation ViewController

#pragma mark - 懒加载

- (NSFetchedResultsController *)fetchedResultsController {
    if (_fetchedResultsController == nil) {
        
        NSLog(@"%s", __FUNCTION__);
        NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass([User class])];
        // 必须设置排序
        NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
        // 设置排序
        fetchRequest.sortDescriptors = @[sortDesc];
        
        AppDelegate *app = [UIApplication sharedApplication].delegate;
        
        // sectionNameKeyPath传nil表示只有一个组
        _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:app.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
        
        // 设置代理
        _fetchedResultsController.delegate = self;
        
        // 侦听数据变化
        [_fetchedResultsController performFetch:nil];
    }
    return _fetchedResultsController;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self fetchedResultsController];
    
}

#pragma mark - NSFetchedResultsControllerDelegate
// CoreData内容将要变化的时候触发
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
    
    NSLog(@"%s", __FUNCTION__);
    [self.tableView beginUpdates];
}

// 数据库内容发生变化的时候触发
- (void)controller:(NSFetchedResultsController *)controller
   didChangeObject:(id)anObject
       atIndexPath:(NSIndexPath *)indexPath
     forChangeType:(NSFetchedResultsChangeType)type
      newIndexPath:(NSIndexPath *)newIndexPath {
    
    NSLog(@"%s", __FUNCTION__);
    // type 增删改查
    // 插入
    if (type == NSFetchedResultsChangeInsert) {
        [self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    
    // 删除
    else if (type == NSFetchedResultsChangeDelete) {
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    
    // 移动
    else if (type == NSFetchedResultsChangeMove) {
        // 删除旧的
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        // 插入新的
        [self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    
    // 更新
    else if (type == NSFetchedResultsChangeUpdate) {
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    
}

// CoreData内容已经发生了变化的时候触发
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
    
    NSLog(@"%s", __FUNCTION__);
    [self.tableView endUpdates];
}


#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSLog(@"%s", __FUNCTION__);
    NSLog(@"组数:%ld",[[[self fetchedResultsController] sections] count]);
    // 有多少组
    return [[[self fetchedResultsController] sections] count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    
    NSLog(@"%s", __FUNCTION__);
    id <NSFetchedResultsSectionInfo> sectionInfo = [[[self fetchedResultsController] sections] objectAtIndex:section];
    // 每组有多少行
    return [sectionInfo numberOfObjects];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog(@"%s", __FUNCTION__);
    static NSString *identifier = @"identifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    User *user = [self.fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = [NSString stringWithFormat:@"--%@--%@",[user valueForKey:@"name"],[user valueForKey:@"phone"]];
    return cell;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值