Dav*_*ave 5 core-data one-to-many uitableview nsfetchedresultscontroller ios
我的核心数据模型如下所示:
article <--->> category
Run Code Online (Sandbox Code Playgroud)
是否可以远程使用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
Run Code Online (Sandbox Code Playgroud)
具体来说,我对(边缘?)情况感兴趣,其中每个UITableView部分都有一个唯一的标题(例如,"Category 1","Category 2"),但同一个对象可以存在于多个部分中(例如,文章A存在在第1类和第2类).
我已经浏览了Apple的核心数据文档,花了两天时间在这里阅读问题,但是,唉,没有运气,甚至不知道这是否可行,更不用说如何实现它了.感谢您对以前回答的问题的任何帮助或指示.我当然找不到它.
是的,这很容易,但有一百万种方法可以做到.
您的视图控制器应该是该数据源的"数据源" UITableView,并返回有关行数的信息,然后返回每个行的内容.
在tableview中有一个"部分"的概念,您可以选择为每个类别选择一个.
例如,您可以创建一个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;
}
Run Code Online (Sandbox Code Playgroud)
您可以阅读有关这些方法的文档,以了解如何进一步自定义它.
| 归档时间: |
|
| 查看次数: |
4229 次 |
| 最近记录: |