美文网首页about iOSiOS开发技巧easy
NSFetchedResultsController + Cor

NSFetchedResultsController + Cor

作者: _skye | 来源:发表于2015-07-10 10:45 被阅读2344次

    1.使用场景

        从coreData中获取存储的数据时,使用谓词NSpredicte进行筛选,排序. 如果筛选的数据需要分组或者分页,就需要对数据再次筛选,使用一些算法也可以实现,但是内存消耗很大,并且逻辑不完善可能会出现其他问题.iOS提供的NSFetchedResultsController,提供高效的查询分类功能,并把数据以分组的形式 展示在 UITableView中.

    如:存储在coreData中的节数据,需要取出该课程下所有节 并按章节分组:

    按章节分组的 课程列表

        在修改数据时, NSManagedObjectContext 数据发生改变变, NSFetchedResultsController可接收到通知,执行代理方法以帮助UITableView显示的数据与coreData存储数据保持一致.

    2.使用方法

    1) 在使用NSFetchedResultsController的相关属性时,需要先创建一个全局的fetchedResultsController

    //用来存储查询并适合TableView来显示的数据

    @property(nonatomic,strong)NSFetchedResultsController *fetchedResultsController;

    //通过实体名获取请求

    NSFetchRequest*request = [[NSFetchRequest alloc]initWithEntityName:@"SectionEntity"];

    request.predicate= [NSPredicate predicateWithFormat:@"section_course.courseId = %d",courseId];

    //定义分组和排序规则(按章分组,章节均是 升序 排列)

    NSSortDescriptor*sortDescriptor1 = [[NSSortDescriptor alloc]initWithKey:@"chapterNum" ascending:ascending1];

    NSSortDescriptor*sortDescriptor2= [[NSSortDescriptor alloc]initWithKey:@"sectionNum" ascending:ascending2];

    //把排序和分组规则添加到请求中

    [requestset SortDescriptors:@[sortDescriptor1,sortDescriptor2]];

    //把请求的结果转换成适合tableView显示的数据

    self.fetchedResultsController=[[NSFetchedResultsController alloc] initWithFetchRequest:requestmanagedObjectContext:kManagedObjectContext sectionNameKeyPath:@"chapterNum" cacheName:nil];


    ... fetchedResultsController创建的相关参数:

    1) NSFetchRequest: 获取对象的请求用于获取对象. 可以设置request的entityName, predicate以及sortDescriptors等属性圈定对象并排序.

    2) NSManagedObjectContext: 上下文,持有获取的对象. 通过上下文可以操作coreData,修改数据,但是如果未save,只是修改了内存中数据,并未保存到磁盘.

    3) sectionNameKeyPath: 获取的对象进行分组的参数.

    4) cacheName:缓存名字.个人理解:只缓存部分数据在磁盘上面,在需要请求时,根据时间戳检查本地缓存的数据,但是处理任何非法的或任务就不检查,可以设置为nil.(API解释: cacheName - Section info is cached persistently to a private file under this name. Cached sections are checked to see if the time stamp matches the store, but not if you have illegally mutated the readonly fetch request, predicate, or sort descriptor.)

    ... NSFetchedResultsController 一个缺陷: :

    使用 sortKey1 作为分组依据,就必须得使用 sortKey1 作为第一排序依据。

    如: 使用 chapterSeq 章节号 分组, 组别 按照 章节号 排序

    使用chapterName 章节名 分组, 组别 按照 章节名 排序.

    以下例举两种情况:

    (1)可作为分组的 参数 未作为第一排序依据,惊吓如下:(出现率100%)

    因:

    作为分组的 参数 未作为第一排序依据

    果:

    以上排序引发的混乱

    (2)使用可作为分组的另一参数,惊吓如下:(出现率5%)

    因:

    可作为分组的另一参数

    果:

    另一参数分组 引发的混乱

    2) 使用NSFetchedResultsController的相关属性/方法,在UITableview中展示

    UITableView 代理方法:

    - (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView

    {

    //我们的数据中有多少个section, fetchedResultsController中的sections方法可以以数组的形式返回所有的section

    //sections数组中存的是每个section的数据信息

    if(nil==_fetchedResultsController) {

    return 0;

     }

    NSArray*sections = [self.fetchedResultsControllersections];

    return sections.count;

    }

    - (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section

    {

    NSArray*sections = [self.fetchedResultsControllersections];

    id <NSFetchedResultsSectionInfo> sectionInfo = sections[section];

    //返回每个section中的元素个数

    return[sectionInfo numberOfObjects];

    }

    -(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath

    {

    //通过[self.fetchedResultsController objectAtIndexPath:indexPath]直接获取对象

    MCVideoCacheEntity*videoEntity = [self.fetchedResultsController objectAtIndexPath:indexPath];

    if(videoEntity ==nil) {

    return nil;

     }

    //....................................中间省略

    }

    补充:

    需要的其他信息可以在以下相关属性/方法中查找:

    NSFetchedResultsController属性 , 方法

    NSFetchedResultsSectionInfo 属性 , 方法

    如:[sectionInfo name] 可以获取分组的组信息:

    chapterName作为分组依据,结果即为章名;

    chapterNum作为分组依据,结果即为章号;

    3) 添加NSFetchedResultsController的代理方法,帮助UITableView显示的数据与coreData存储数据保持一致

    //当CoreData的数据正在发生改变时,FRC产生的回调("controllerWillChangeContent"与"controllerDidChangeContent"此处不写,添加行暂未出现异常,添加一个新的分区数据可能会crash)

    - (void)controllerWillChangeContent:(NSFetchedResultsController*)controller {

    [_downLoadListTbl beginUpdates];

    }

    //分区改变状况

    - (void)controller:(NSFetchedResultsController*)controller didChangeSection:(id)sectionInfo

    atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {

    switch(type) {

    caseNSFetchedResultsChangeInsert:

    [self.downLoadListTbl insertSections:[NSIndexSet indexSetWithIndex:sectionIndex]

    withRowAnimation:UITableViewRowAnimationFade];

    break;

    caseNSFetchedResultsChangeDelete:

    [self.downLoadListTbl deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex]

    withRowAnimation:UITableViewRowAnimationFade];

    break;

    default:

    break;

     }

    }

    //数据改变状况

    - (void)controller:(NSFetchedResultsController*)controller didChangeObject:(id)anObject

    atIndexPath:(NSIndexPath*)indexPath forChangeType:(NSFetchedResultsChangeType)type

    newIndexPath:(NSIndexPath*)newIndexPath {

    UITableView*tableView =self.downLoadListTbl;

    switch(type) {

    caseNSFetchedResultsChangeInsert:

    //让tableView在newIndexPath位置插入一个cell

    [tableViewinsertRowsAtIndexPaths:[NSArrayarrayWithObject:newIndexPath]

    withRowAnimation:UITableViewRowAnimationFade];

    break;

    caseNSFetchedResultsChangeDelete:

    [tableViewdeleteRowsAtIndexPaths:[NSArrayarrayWithObject:indexPath]

    withRowAnimation:UITableViewRowAnimationFade];

    break;

    caseNSFetchedResultsChangeUpdate:

    //让tableView刷新indexPath位置上的cell

    [tableViewreloadRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationNone];

    break;

    caseNSFetchedResultsChangeMove:

    [tableViewdeleteRowsAtIndexPaths:[NSArrayarrayWithObject:indexPath]

    withRowAnimation:UITableViewRowAnimationFade];

    [tableViewinsertRowsAtIndexPaths:[NSArrayarrayWithObject:newIndexPath]

    withRowAnimation:UITableViewRowAnimationFade];

    break;

     }

    }

    //当CoreData的数据完成改变是,FRC产生的回调

    - (void)controllerDidChangeContent:(NSFetchedResultsController*)controller {

    [self.downLoadListTbl endUpdates];

    }

    ........................................................................................................................................

    本文 NSFetchedResultsController + CoreData + UITableView的完美结合,只是在基本功能上简单介绍,更完美的功能还待使用者发掘......(欢迎批评指正~~)

    相关文章

      网友评论

      本文标题:NSFetchedResultsController + Cor

      本文链接:https://www.haomeiwen.com/subject/urddqttx.html