如何将数据添加到 tableView 并重新加载?

问题描述

我正在尝试通过从另一个 viewController 的 segue 发送数据来将单元格添加到 viewController 中的 tableView。

class FavoritesViewController: UIViewController {
    
    var shops = [
        "hello world","hello world","hello world"
    ]
    
    @IBOutlet weak var table: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        table.delegate = self
        table.dataSource = self
        table.reloadData()
    }
    
}

//protocol FavoritesDelegate: class {
//    func add(_ shopName: String)
//}

extension FavoritesViewController: UITableViewDelegate,UITableViewDataSource{
    
    func add(_ shopName: String) {
        print(shopName)
        shops.append(shopName)
    }
    
    
    func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
        return shops.count
    }
    
    func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell",for: indexPath)
        cell.textLabel?.text = shops[indexPath.row]
        return cell
        
    }
    
    // define the action. In this case "delete"
    func tableView(_ tableView: UITableView,editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .delete
    }
    
    // do the actual deleting
    func tableView(_ tableView: UITableView,commit editingStyle: UITableViewCell.EditingStyle,forRowAt indexPath: IndexPath) {
        
        if editingStyle == .delete {
            tableView.beginUpdates()
            
            shops.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath],with: .fade)
            
            tableView.endUpdates()
        }
        

    }
    
    
}

这是另一个 viewController 中的函数调用(准备):

 override func prepare(for segue: UIStoryboardSegue,sender: Any?) {
    
   
        favoritesDestinationVC = segue.destination as! FavoritesViewController
        favoritesDestinationVC.add(shopName!)
        
        
    
}

我知道是什么导致了错误(favoritesDestinationVC 创建了一个 tableView 为零的新实例),但我不知道如何解决。关于如何以这种方式向 tableView 添加条目(并随后更新表格)而我的应用程序不崩溃的任何想法?

解决方法

将您的商店变量设为公开,然后在 segue 准备回调中直接使用它。首先检查变量是否具有除 nil 以外的有效值,如果是,则继续以避免崩溃。您可以使用 if 语句进行验证,如示例代码中所示。或者您可以使用选项来避免崩溃。请参阅下面的代码。

override func prepare(for segue: UIStoryboardSegue,sender: Any?) {

    if segue.destination is FavoritesViewController {
        let destinationVC = segue.destination as? FavoritesViewController // Use optionals which has ? (question mark)
        // To avoid crashes check if shopName has a valid value other than nil
        if let newShopName = shopName {
            // It is possible that the "shopName" has a nil value when the program reaches here.
            // That's why we will use the verified "newShopName" instead of "shopName" itself to avoid any crash.
            destinationVC?.shops.append(newShopName) // What I recommend,if not convenient for you just delete this line,// destinationVC?.add(newShopName) // after deleting the recommended line,uncomment this line for your convenience.
        }
    }

}