获取的属性将起作用,实际上我在我自己的项目中使用了它,它具有需要按“添加日期索引”排序的 Post->Comment 关系。
有许多警告:您不能在可视化编辑器中指定排序描述符,而必须在代码中指定它。
我用这样的东西
// Find the fetched properties, and make them sorted...
for (NSEntityDescription *entity in [_managedObjectModel entities])
{
for (NSPropertyDescription *property in [entity properties])
{
if ([property isKindOfClass:[NSFetchedPropertyDescription class]])
{
NSFetchedPropertyDescription *fetchedProperty = (NSFetchedPropertyDescription *)property;
NSFetchRequest *fetchRequest = [fetchedProperty fetchRequest];
// Only sort by name if the destination entity actually has a "index" field
if ([[[[fetchRequest entity] propertiesByName] allKeys] containsObject:@"index"])
{
NSSortDescriptor *sortByName = [[NSSortDescriptor alloc] initWithKey:@"index"
ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortByName]];
}
}
}
}
在我的帖子实体中,我有一个名为“sortedComments”的获取属性,其定义为:
post == $FETCH_SOURCE
帖子有一对多“评论”关系,评论有“帖子”逆
与此处的其他答案相反:使用这样的获取属性的好处是,CoreData 负责缓存并使缓存无效,因为评论或拥有它们的帖子发生了变化。