我的核心数据模型如下所示:
article <--->> category
是否可以远程使用NSFetchedResultsController
生成一个看起来像这样的 UITableView?
Category 1
- Article A
- Article B
- Article C
Category 2
- Article A
- Article D
- Article E
- Article F
Category 3
- Article B
- Article C
具体来说,我对(边缘?)情况感兴趣,其中每个 UITableView 部分都有唯一的标题(例如,“类别 1”、“类别 2”),但同一对象可以存在于多个部分中(例如,存在文章 A在类别 1 和类别 2 中)。
我浏览了苹果的核心数据文档,并花了两天时间仔细研究这里的问题,但可惜的是,甚至没有找到这是否可能的运气,更不用说如何实现它了。感谢您提供任何帮助或指向先前回答的问题。我当然找不到。
是的,这很容易,尽管有一百万种方法可以做到。
您的视图控制器应该是UITableView
,并返回有关行数的信息,然后返回每行的内容。
表格视图中有一个“部分”的概念,您可以选择为每个类别都有一个“部分”。
例如,您可以创建一个NSFetchedResultsController
找到要显示的类别,并使用它来填充表视图部分,然后每个类别将具有文章多对多关系,以填充每个部分中的行。
像这样的东西应该可以帮助您开始(假设您的类别和文章实体都包含title
财产):
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// return the number of categories
[[self.categoryResultsController fetchedObjects] count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
// return the title of an individual category
[[self.categoryResultsController.fetchedObjects objectAtIndex:section] valueForKey:@"title"];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// return the number of articles in a category
MyCategory *category = [self.categoryResultsController.fetchedObjects objectAtIndex:section];
return category.articles.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// fetch a cached cell object (since every row is the same, we re-use the same object over and over)
static NSString *identifier = @"ArticleCellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
}
// find the category and article, and set the text of the cell
MyCategory *category = [self.categoryResultsController.fetchedObjects objectAtIndex:indexPath.section];
cell.textLabel.text = [[category.articles objectAtIndex:indexPath.row] valueForKey:@"title"];
return cell;
}
您可以阅读有关这些方法的文档,以了解如何进一步自定义它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)