2
我的數據模型很簡單,就像一個普通的詞典:CoreData實體部分來的UITableView
的字母是英文字母,單詞是詞典的詞彙和定義。我的目標是在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。
問題是如何獲取某一節中的行數,以及如何引用數據以將它們放入一行中?
這看起來差不多正確,但是您必須添加與sectionNameKeyPath對應的*第一個排序描述符*。 –
如果排序順序不受影響,則不必明確指定。因此,我對字詞值和相關字母的假設。然而,你的建議會使它更加正確,我會更新這個例子。 –
你說得對,排序是一樣的。 –