【发布时间】:2021-05-20 04:36:56
【问题描述】:
当我将 textLabel 中的文本添加到表格时,应用程序崩溃。我知道 Swift 对错误的 indexPath 发誓,但我不明白错误在代码中的确切位置
我的 coreData 也不起作用。谁能说我做错了什么?
视图控制器
import UIKit
import CoreData
class NewViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let managedContext = (UIApplication.shared.delegate as!
AppDelegate).persistentContainer.viewContext
var messages: [MessageEntitty] = []
@IBOutlet weak var tablr: UITableView!
@IBOutlet weak var text: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
self.tablr.delegate = self
self.tablr.dataSource = self
tablr.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
@IBAction func button(_ sender: Any) {
text.text .isEmpty ? alert() : actiontForText()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = messages[indexPath.row].name
return cell
}
private func alert(){
let alert = UIAlertController(title: "No Text", message: "Print your message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .cancel))
present(alert, animated: true)
}
private func actiontForText(){
guard let message = text.text, !message.isEmpty else { return }
self.save(message)
self.tablr.insertRows(at: [IndexPath(row: messages.count-1, section: 0)], with: .automatic)
self.tablr.scrollToRow(at: IndexPath(row: messages.count-1, section: 0), at: .bottom, animated: true)
text.text = ""
}
}
保存方法
func save(_ newMessage: String){
guard let entityDescription = NSEntityDescription.entity(forEntityName: "MessagesEntity", in: managedContext) else { return }
let message = NSManagedObject(entity: entityDescription, insertInto: managedContext)
as! MessageEntitty
message.name = newMessage
do{
try managedContext.save()
messages.append(message)
self.tablr.insertRows(at: [IndexPath(row: messages.count-1, section: 0)], with: .automatic)
} catch let error{
print(error.localizedDescription)
}
}
【问题讨论】:
-
你可以为
save方法添加实现吗,self.save(message) -
添加保存方法的实现,self.save(message)
-
您在
save(方法中调用了两次self.tablr.insertRows(at: [IndexPath(row: messages.count-1, section: 0)], with: .automatic),在actiontForText中调用了一次self.save(message)删除其中一个 -
我必须说
let message = NSManagedObject将其保存到managedObjectContext并将其直接附加到数组可能容易出错,相反,您可以在使用fetchRequest插入后获取消息并更新 @ 987654332@ 数组,然后调用self.tablr.insertRows或者您可以随时使用nsfetchedresultscontroller