【发布时间】:2021-05-18 19:05:01
【问题描述】:
我正在尝试制作一个简单的“联系人”应用程序。一切正常,但我找不到按字母顺序将数据从 CoreData 写入 tableView 的方法。
我希望人们将他们的电话号码和姓名保存在 CoreData 中,然后,他们将作为 Person 对象添加到数组中。另外,我想将名称写入 tableView 单元格标签。如您所知,这些名称必须按字母顺序排列。
我使用 MVC 创建了应用程序并创建了一个空数组来保存用户的电话号码和姓名。数组的类型是Person。
//Like below.
// I hold the informations in this array.
var personList = [Person]()
//here is the cell format I am using in the app.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath) as! TableViewCell
let person = personList[indexPath.row]
cell.imageBackground.tintColor = cell.backgroundColors.randomElement()
cell.imageLabel.text = String(person.personFirstLetter.first!)
cell.nameLabel.text = person.personName
return cell
}
//this is how I get data from the user.
@objc func getData() {
personList.removeAll(keepingCapacity: false)
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "People")
fetchRequest.returnsObjectsAsFaults = false
do {
let results = try context.fetch(fetchRequest)
for result in results as! [NSManagedObject]{
if let name = result.value(forKey: "name") as? String{
if let phoneNumber = result.value(forKey: "number") as? String{
if let firstLetter = result.value(forKey: "letter") as? String{
personList.append(Person(personName: name, personNumber: phoneNumber, personFirstLetter: firstLetter))
}
}
}
}
} catch {
print(error.localizedDescription)
}
我实际上不知道在这里分享什么以及如何或在哪里采用字母排序。
谢谢大家。干杯!
【问题讨论】: