NSFetchedResultsController和TableViews

时间:2011-05-23 09:41:32

标签: objective-c ios uitableview core-data nsfetchedresultscontroller

我正在尝试将Core Data与NSFetchedResultsController一起使用。

数据模型分为“树级”。

父母 - > (很多)儿童 - > (很多)孙子

在表格视图中,我想将父项的所有Childs显示为section,将GrandChildrens显示为cell。我很难弄清楚如何解决这个问题。

任何建议都将受到赞赏。

修改 数据模型:

Parent:
name NSString*
Id NSNumber*
child NSSet* (set of childs)

Child:
name NSString*
childId NSNumber*
parent Parent*
childrensChilds NSSet* (set of childrensChilds)

ChildrensChild:
name NSString*
ChildrensChildId NSNumber*
parentChild *Child

FetchRequest:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Child" inManagedObjectContext:moc];
[fetchRequest setEntity:entity];

NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"ChildId" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"parent.parentId = %@", self.parentId];
[fetchRequest setPredicate:predicate];

[fetchRequest setFetchBatchSize:20];

NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:moc sectionNameKeyPath:nil cacheName:@"Childrens"];
self.fetchedResultsController = theFetchedResultsController;
fetchedResultsController.delegate = self;

[fetchRequest release];
[theFetchedResultsController release];

然后我想创建包含子名称的节标题和要在childrenschild之后命名的单元格。

1 个答案:

答案 0 :(得分:0)

将fetched results controller(FRC)与tableview一起使用时,将fetch实体设置为将填充行的实体。毕竟,部分是可选的,但总是需要行。

您需要做的第一件事就是在数据模型中设置相互关系,如下所示:

Parent<-->>Child<-->>GrandChild

...这允许您从任何实体开始横向对象,例如如果您有一个Grandchild对象,则使用密钥路径'parentChild.parent'(或您称之为关系的任何对象)通过遍历Parent对象来到达相关的Child对象。

要根据需要配置tableview,您可以将获取实体设置为GrandChild,将谓词设置为parentChild.parent.id=%@,然后将FRC sectionNameKeyPath设置为parentChild.name

但是,您可能想重新考虑整个设计。树结构的简单数据模型是:

Person{
  name:string
  id:number
  parent<<-->Person.children
  children<-->>Person.parent
}

孙子是一个孩子,两个人往下穿过,祖父母是父母两个人。一旦你有了任何特定的Person对象,那么在tableview中显示将是微不足道的。节名称是'children'关系的排序数组,行将按每个子节点自己子节点的数组排序。

你根本不需要提取物。