问题描述
我通常只有一个属性来排序by,并使用 sectionNameKeyPath:
生成节。但我的排序属性是即时计算的,我似乎不能得到 fetchedResultsController
正确使用...
更新:在下面使用的建议,我真的很近到预期的功能。我添加了一个类别到 NSDate
,返回一个天前数字;这里给出了基于这些数字的部分:
NSFetchedResultsController * aFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest :fetchRequest
managedObjectContext:managedObjectContext
sectionNameKeyPath:@myDateAttribute.daysAgo
cacheName:@Root];
这里是我被困的地方:我不需要他们按天前排序需要通过基于实体中的其他属性的一些计算来排序。所以我不能只是调用自定义类别方法,我需要调用一个方法与参数,像这样:
[myDateAttribute orderingRoutine:thisObject.value]
或类似的东西。我希望这有一定的意义。非常感谢您帮忙:)
您可以尝试以下方法。
在任务实体中将临时属性添加到核心数据模型。然后实现
- (void)awakeFromFetch
方法在任务NSManagedObject类中。请参阅其文档。在方法中,您可以使用其他属性的值为transient属性设置值。注意,你可以做什么,但是这在文档中有很好的解释(最值得注意的是,你不能修改关系或传递参数;但是,如果你可以计算你的瞬时属性只使用其他属性/关系应该是完美的)。
一旦你这样做,你只需使用transient属性作为传递的属性,以获得这些部分。
I'm making a sectioned table with fetched results, but am having a hard time getting custom sections worked out.
Normally one would just have an attribute to sort by, and use
sectionNameKeyPath:
to generate the sections. But my sorting attribute is calculated on the fly, and I can't seem to get thefetchedResultsController
to use it correctly...Update: Using jbrennan's advice below, I'm really close to the intended functionality. I've added a Category to
NSDate
that returns a "days ago" number; putting that in here gives me sections based on those numbers:NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:@"myDateAttribute.daysAgo" cacheName:@"Root"];
Here's where I'm stuck: I don't need them sorted by "days ago," I need them sorted via some calculations based on other attributes in the entity. So I can't just call that custom Category method, I need to call a method with arguments, like so:
[myDateAttribute sortingRoutine:thisObject.value]
Or something like that. I hope that makes some degree of sense. Thanks a ton if you can help :)
解决方案You can try the following.
Add a transient attribute to your core data model in the Task entity. Then implement the
- (void)awakeFromFetch
method in your Task NSManagedObject class. See its documentation. Within the method you are allowed to set a value for the transient property using the values of the other properties. Note that there are some restrictions on what you can do, but this is well explained in the documentation (most notably you can not modify relationships or pass arguments; however, if you can compute you transient property using only the values of the other properties/relationships it should be perfectly fine).
Once you have done this, you simply use the transient property as the attribute you pass to get back the sections.
这篇关于使用NSFetchedResultsController的自定义部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!