【问题标题】:iOS 5 - Dividing UITableView into sections by Core Data AttributeiOS 5 - 按核心数据属性将 UITableView 划分为多个部分
【发布时间】:2012-05-28 23:30:32
【问题描述】:

我是 Core Data 的新手,所以请多多包涵。 ;)

在我的数据模型中,我有一个名为“Item”的实体,具有 2 个属性,“Section”和“Name”。我已经使用名称填充了 UITableView(我的主视图),但我想将 TableView 分为 3 个不同的部分,由属性“部分”确定。我在想“section”属性应该是一个整数,所以 0 是第一个部分,1 是第二个部分,2 是第三个部分。

我真的不知道如何将 TableView 分成几个部分。我正在使用 NSFetchedResultsController。这是当前代码。

- (void)setupFetchedResultsController
{
// 1 - Decide what Entity you want
NSString *dbEntityName = @"Item"; // Put your entity name here

// 2 - Request that Entity
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:dbEntityName];

// 3 - Filter it if you want
//request.predicate = [NSPredicate predicateWithFormat:@"Item.name = what"];

// 4 - Sort it if you want
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name"
                                                                                 ascending:YES
                                                                                  selector:@selector(localizedCaseInsensitiveCompare:)]];
// 5 - Fetch it
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                                    managedObjectContext:self.managedObjectContext
                                                                      sectionNameKeyPath:nil
                                                                               cacheName:nil];
[self performFetch];
}

另外,我想知道 Xcode 中数据模型中的 Fetch Request 模板是否会有所帮助。我看到了如何创建获取请求,但没有看到如何让它对获取的内容做任何事情(例如:将获取的数据放入某个 TableView 部分。)

如果有人能帮忙,将不胜感激。

【问题讨论】:

    标签: ios uitableview core-data nsfetchedresultscontroller sections


    【解决方案1】:

    创建 NSfetchedResultsController 时需要选择 sectionNameKeyPath。这应该指向模型对象中的一个属性,该属性对于同一部分中的每个项目都是相同的。

    要显示节标题,请确保按照 NSfetchedResultsController 文档中的示例实现所有 tableView 数据源方法。

    【讨论】:

    • 非常感谢您的回复! :) 你有没有机会为我提供一个例子?我不确定要为 sectionNameKeyPath 写什么。
    • 在您的情况下,部分名称键路径将是“部分”。这正是它听起来的样子 - 导致部分名称的关键路径。整数可能不是最好的选择,因为这不会使节标题非常吸引人。
    • 嗯,好的,谢谢。它只是 sectionNameKeyPath:@"section" 吗?这似乎很容易。对标题使用字符串会更好吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-07
    • 2011-11-02
    相关资源
    最近更新 更多