【问题标题】:Cant add new row in table from textLabel无法从 textLabel 在表格中添加新行
【发布时间】: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

标签: swift core-data


【解决方案1】:

你可以这样做:

/// ...
    var messages: [MessageEntity] = [] {
         didSet {
              tablr.reloadData()
         }
    }
/// ...

private func save(_ newMessage: String){
    let newMessageEntity = MessagesEntity(context: managedContext)
    newMessageEntity.name = newMessage
    
    do {
        try managedContext.save()
        updateUI()
    } catch let error{
        print(error.localizedDescription)
    }
}

private func updateUI() {
    messages = loadContext()
}

// generic function to load all kinds of [NSManagedObject]
private func loadContext<T: NSManagedObject>() -> [T] {
    let request: NSFetchRequest<T> = NSFetchRequest<T>(entityName: String(describing: T.self))
    do {
        return try managedContext.fetch(request)
    } catch {
        print("error: \(error)")
    }
    return []
}

private func actiontForText() {
    guard let message = text.text, !message.isEmpty else { return }
    save(message)
    
    tablr.scrollToRow(at: IndexPath(row: messages.count-1, section: 0), at: .bottom, animated: true)
    text.text = ""
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-02
    • 2016-06-26
    • 2015-08-22
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多