iOS开发NSFetchedResultsController的使用CoreData和TableView数据同步更新

1、效果

 

2、代码

#import "ViewController.h"
#import "Student+CoreDataProperties.h"
#define CScreenWidth        [[UIScreen mainScreen] bounds].size.width
#define CScreenHeight       [[UIScreen mainScreen] bounds].size.height

#define Model_Name @"Student"
@interface ViewController ()<NSFetchedResultsControllerDelegate,UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)NSFetchedResultsController *fetchedResultsController;
@property(nonatomic,strong)UITableView *tableView;
@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"===%@",NSHomeDirectory());
    for (int i=0; i<3;i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn addTarget:self action:@selector(addDataClick:) forControlEvents:UIControlEventTouchUpInside];
        [btn setTitle:@[@"添加",@"删除",@"修改"][i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        btn.frame = CGRectMake(CScreenWidth/3*i, 50, CScreenWidth/3, 40);
        btn.tag = i;
        [self.view addSubview:btn];
    }

    [self.view addSubview:self.tableView];
}
- (void)addDataClick:(UIButton *)btn{
    switch (btn.tag) {
        case 0:
            [self addData];
            break;
        case 1:
            [self deleData];
            break;
        default:
            [self exchangeData];
            break;
    }
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 100, CScreenWidth, CScreenHeight) style:0];
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}

- (NSFetchedResultsController *)fetchedResultsController{
    if (!_fetchedResultsController) {
        NSFetchRequest *fetchReq = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:Model_Name inManagedObjectContext:self.managedObjectContext];
        [fetchReq setEntity:entity];
        
        //排序规则
        NSSortDescriptor *sortDes = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
        [fetchReq setSortDescriptors:[NSArray arrayWithObject:sortDes]];
        
        //筛选数据规则
        NSPredicate *preDic = [NSPredicate predicateWithFormat:@"age = %@",@"13"];
        [fetchReq setPredicate:preDic];
        [fetchReq setFetchBatchSize:20];
        _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchReq managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"students"];
        _fetchedResultsController.delegate = self;
        
        NSError *error = NULL;
        if (![_fetchedResultsController performFetch:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
    
    return _fetchedResultsController;
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [self.tableView reloadData];
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[[self.fetchedResultsController sections] objectAtIndex:section] numberOfObjects];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (nil == cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
    }
    
    [self configureCell:cell atIndexPath:indexPath];
    
    return cell;
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    Student *student = [self.fetchedResultsController objectAtIndexPath:indexPath];
    cell.imageView.backgroundColor = [UIColor redColor];
    cell.textLabel.text = student.name;
    cell.detailTextLabel.text = student.age;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}

//添加一条数据
- (void)addData{
    Student *newEintity = [NSEntityDescription insertNewObjectForEntityForName:Model_Name inManagedObjectContext:self.managedObjectContext];
    newEintity.name = @"张三";
    newEintity.age = @"13";
    [self saveContext];
}

//删除一条数据
- (void)deleData{
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:Model_Name];
    NSPredicate *predic = [NSPredicate predicateWithFormat:@"age = %@",@"13"];
    request.predicate = predic;
    NSArray *arr = [self.managedObjectContext executeFetchRequest:request error:nil];
    if (arr.count>0) {
        [self.managedObjectContext deleteObject:arr.firstObject];
        [self saveContext];
    }
}
//删除和修改数据时先查找
//改变一条数据
- (void)exchangeData{
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:Model_Name];
    NSPredicate *predic = [NSPredicate predicateWithFormat:@"age = %@",@"13"];
    request.predicate = predic;
    NSArray *arr = [self.managedObjectContext executeFetchRequest:request error:nil];
    if (arr.count>0) {
        Student *objc = (Student *)arr.firstObject;
        objc.name = @"李四";
        objc.age = @"13";
        [self saveContext];
    }
}

//存储路径
- (NSURL *)applicationDocumentsDirectory {
    NSLog(@"===%@",NSHomeDirectory());
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

//创建模型对象
//作用:添加实体的属性,建立属性之间的关系
//操作方法:视图编辑器,或代码
- (NSManagedObjectModel *)managedObjectModel {
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"School" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

//创建数据库助理
//作用:设置数据存储的名字,位置,存储方式,和存储时机
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"School.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}

//生成上下文,关联数据库助理
//作用:插入数据,查询数据,删除数据,更新数据
- (NSManagedObjectContext *)managedObjectContext {
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support
//保存
- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end

 

posted @ 2018-01-17 14:51  ForeverGuard  阅读(238)  评论(0编辑  收藏  举报