gpt4 book ai didi

swift - 带有部分的 UITableView 的 CoreData 实体

转载 作者:搜寻专家 更新时间:2023-10-31 22:34:35 26 4
gpt4 key购买 nike

我的数据模型非常简单,就像一本普通的词典:

enter image description here

字母是字母表中的字母,单词是字典中的单词和定义。我的目标是在 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,每个标题为 a 到 z。

问题是如何获取一个部分中的行数以及如何引用数据以将它们排成一行?

最佳答案

我不认为这段代码会做你想做的事。通常,用于构造填充 UITableViewUICollectionViewNSFetchedResultsControllerNSFetchRequest 必须获取您要获取的实体类型实际上想要显示(或者事情变得复杂)。你试过这样的事情吗?

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)")
}

假设您的单词值和关联的字母是正确的,我认为这应该可以满足您的要求。还值得注意的是,cacheName 在您的应用程序中必须是唯一的,因此您可能需要比简单的 "dict" 更复杂的东西。

关于swift - 带有部分的 UITableView 的 CoreData 实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32924666/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com