下面的代码调用coredata并将字符串打印在标签中。
@IBOutlet var displayL: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
user = coreDataHandler.getSortedData()
for i in user! {
displayL.text = String("\(displayL.text ?? "")\nCourse: \(i.username!) Score: \(i.password!)")
}}
这有效,我想将其传输到一个tableview单元格,但是现在我无法使用。表格视图中什么都没有显示。我的tableview代码如下。我只想获取uitableview单元格,并为每个单元格显示一个条目。
import UIKit
import CoreData
class allScoresViewController: UIViewController, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var tazbleView : UITableView!
var itemsName : [NSManagedObject] = []
var textFieldz : UITextField!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemsName.count
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let appD = UIApplication.shared.delegate as! AppDelegate
let context = appD.persistentContainer.viewContext
let FetchRequest = NSFetchRequest<NSManagedObject>(entityName: "User")
do {
itemsName = try context.fetch(FetchRequest)
}catch {
print("Ashley Tisdale")
}
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete {
let appD = UIApplication.shared.delegate as! AppDelegate
let context = appD.persistentContainer.viewContext
context.delete(itemsName[indexPath.row])
itemsName.remove(at: indexPath.row)
do {
try context.save()
}
catch {
print("Jessica Alba")
}
self.tazbleView.reloadData()
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for : indexPath)
let user = itemsName[indexPath.row]
cell.textLabel?.text = ("\nCourse: \(user.username!) Score: \(user.password!)")
return cell
}
}
答案 0 :(得分:0)
我假设由于您在viewDidAppear
中获取了User实体,所以您要使用的不是coreDataHandle.getSortedData()
。
将itemsName
的声明更改为
var itemsName: [User] = []
和tableView:cellForRowAt:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for : indexPath)
let user = itemsName[indexPath.row]
cell.textLabel?.text = ("\nCourse: \(user.username!) Score: \(user.password!)")
return cell
}
更新
您可能还想更新viewDidAppear
let fetchRequest = NSFetchRequest<User>()