使用Core Data实体更新表节标题的有效方法? [英] Efficient way to update table section headers using Core Data entities?

查看:84
本文介绍了使用Core Data实体更新表节标题的有效方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的UITableView中使用NSFetchedResultsController,它显示了存储在核心数据中的一堆事件。

Im using a NSFetchedResultsController for my UITableView which displays a bunch of events im storing in core data.

我想做的是按相对日期(即今天,明天,本周等)对表格进行分组。每个事件都有一个开始日期,我尝试在名为sectionIdentifier的事件实体中创建一个瞬态属性,该实体将日期转换为相对日期,如上所述,如下所示:

What i am trying to do is group the table by relative date (ie Today, Tomorrow, This Week, etc..). Each event has a start date and i tried creating a transient property in the event entity called sectionIdentifier which converts the date into a relative date as mentioned above like so:

- (NSString*)sectionIdentifier
{    
[self willAccessValueForKey:@"sectionIdentifier"];
NSString *tmp = [self primitiveSectionIdentifier];
[self didAccessValueForKey:@"sectionIdentifier"];

if (!tmp) 
{
    tmp = [Utility formattedDateRelativeToNow:self.startTime];
    [self setPrimitiveSectionIdentifier:tmp];
}
return tmp;
}

问题在于它显然只执行一次且不会更新除非日期改变,这不是我真正期望的。我曾经考虑过重写getStartDate访问器来更新sectionIdentifier,尽管这似乎有点笨拙而且效率低下,因为每次我访问该属性时它将执行此更新

The problem is that it obviously only does this once and doesn't update itself unless the date is changed which i dont really expect. I have thought of overriding the getStartDate accessor to update the sectionIdentifier although this seems a little heavy handed and inefficient as it would perform this update every time i access that property

任何想法?

推荐答案

最好的方法是违反直觉的。无需更改获取的结果控制器或Core Data中的任何内容,您可以使用类别扩展NSDate,使其具有根据适当的日期计算返回值的键名/方法。然后,在获取的结果控制器 sectionNameKeyPath 中包含键名/方法。

The best method for doing this is rather counterintuitive. Instead of changing the fetched results controller or anything in Core Data, you extend NSDate with a category to have a keyname/method that returns a value based on the appropriate date calculation. You then include the keyname/method in the fetched results controller sectionNameKeyPath.

有关如何使用今天,昨天,明天等键名/方法扩展NSDate。

要使用此功能,您只需取回结果控制器获取的实体的日期属性的方法,如下所示:

To use this, you would just take on the method to a date attribute of the entity the fetched results controller fetches like so:

NSFetchedResultsController *frc=[[NSFetchedResultsController alloc] initWithFetchRequest:aFetch 
                                                                    managedObjectContext:aMoc 
                                                                      sectionNameKeyPath:@"startdate.yesterday" 
                                                                               cacheName:nil];

...,这些部分将自动显示。

... and the sections will appear automatically.

这篇关于使用Core Data实体更新表节标题的有效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆