我的核心数据关系提取请求返回 NSSet 对象。自从无序集中的 NSset 以来,如何为 TableView 数据源设置此数据。我可以将 NSSet 转换为 NSArray ,但它会以相同的顺序返回数据。
最佳答案
Apple is clear “数组中对象的顺序未定义。”所以我希望它会改变。
我建议您将 allObjects
数组存储到一个实例变量中,并使用它来实现 numberOfSectionsInTableView()
和其他数据源方法。
您还可以将您的 NSFetchedResultsController
存储在实例变量中并安全地使用它,例如:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rows = 0
if self.fetchedResultsController!.sections!.count > 0 {
let sectionInfo = getSectionInfo(section)
rows = sectionInfo!.numberOfObjects
}
return rows
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let sectionInfo = getSectionInfo(section)
return sectionInfo!.name
}
func getSectionInfo(section: Int) -> NSFetchedResultsSectionInfo? {
var sections: [AnyObject] = self.fetchedResultsController!.sections!
if section < sections.count {
let x = sections[section] as! NSFetchedResultsSectionInfo
return x
}
return nil
}
override func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
return self.fetchedResultsController!.sectionForSectionIndexTitle(title, atIndex: index)
}
override func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
return self.fetchedResultsController!.sectionIndexTitles
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("YourCellIdentifier")! as UITableViewCell
// Use your own NSManagedObject class here...mine is Category
let category = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Category
return cell
}
就我个人而言,我已将上述所有方法编码到我重用的基类中,这样我就可以在每个新 TableView 中实现 cellForRowAtIndexPath()
。我发了a copy on github以防对其他人有用。
关于ios - 我如何从 CoreData 关系设置 UItableView 数据源。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37631763/