我的数据模型非常简单,就像常规单词词典一样:
字母是字母表中的字母,单词是字典的单词和定义。我的目标是在UITableView中显示数据,其中Letter是部分,下面是单词。
我的代码:
var fetchedResultsController: NSFetchedResultsController!
override func viewDidLoad() {
super.viewDidLoad()
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Letter")
let letterSort =
NSSortDescriptor(key: "letterName", ascending: true)
fetchRequest.sortDescriptors = [letterSort]
fetchedResultsController =
NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: context,
sectionNameKeyPath: "letterName",
cacheName: "dict")
fetchedResultsController.delegate = self
do {
try fetchedResultsController.performFetch()
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
}
}
func numberOfSectionsInTableView
(tableView: UITableView) -> Int {
return fetchedResultsController.sections!.count
}
func tableView(tableView: UITableView,
titleForHeaderInSection section: Int) -> String? {
let sectionInfo =
fetchedResultsController.sections![section]
return sectionInfo.name
}
func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
let sectionInfo =
fetchedResultsController.sections![section]
print(sectionInfo.numberOfObjects)
return sectionInfo.numberOfObjects
}
我从教程中学到了这段代码。它似乎工作。节号等于26,每个标题是一个到z。
问题是如何获取节中的行数以及如何引用数据以将它们排成一行?
答案 0 :(得分:2)
我认为这段代码不会做你想要的。通常,用于构建填充NSFetchRequest
或NSFetchedResultsController
的{{1}}的{{1}}必须获取您实际想要显示的实体类型(或事情变得复杂)。你尝试过这样的事吗?
UITableView
假设你的单词值和相关字母是正确的,我认为这应该做你想要的。同样值得注意的是UICollectionView
在您的应用中必须是唯一的,因此您可能需要比简单let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Word")
let letterSort =
NSSortDescriptor(key: "letter.letterName", ascending: true)
let wordSort = NSSortDescriptor(key: "word", ascending: true)
fetchRequest.sortDescriptors = [letterSort, wordSort]
fetchedResultsController =
NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: context,
sectionNameKeyPath: "letter.letterName",
cacheName: "dict")
fetchedResultsController.delegate = self
do {
try fetchedResultsController.performFetch()
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
}
更复杂的内容。