简体   繁体   English

为什么在我保存数据数据并调用 tableview.reloadData() 函数后我的 tabe 视图不会重新加载

[英]Why wont my tabe view reload after i save data data and call the tableview.reloadData() function

I am confused to why my table view is not reloading after i call the tableView.reloadData() function.我很困惑为什么在调用 tableView.reloadData() 函数后我的表视图没有重新加载。 Here is what you should know about my project.这是您应该了解的有关我的项目的信息。 The initial view controller is a tableViewController and when you click the add button in the navigation bar it pulls up presents the "addItemViewController".初始视图控制器是一个 tableViewController,当您单击导航栏中的添加按钮时,它会弹出“addItemViewController”。 It is presented overCurrentContext.它是通过当前上下文呈现的。 Everything to this point works fine, but the part that doesn't work is when you fill out the info in the pop up I created and push the button to save it it saves to the core data fill but when i reload it it doesnt even call that.到目前为止一切正常,但不起作用的部分是当您在我创建的弹出窗口中填写信息并按下按钮以保存它时,它会保存到核心数据填充中,但是当我重新加载它时它甚至没有叫那个。 When i close the app and reload it the data shows up but it doesnt show up when i add it and call the same function.当我关闭应用程序并重新加载它时,数据会显示出来,但是当我添加它并调用相同的函数时它不会显示出来。

import UIKit
import CoreData
protocol reloadTableView: class {
    func reloadTableView()
}
class TableViewController: UITableViewController {
    
    //Global Variables
    let addItemVC = AddItemController()
    var itemArray = [Item]()
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
    override func viewDidLoad() {
        super.viewDidLoad()
        addItemVC.delegate = self
        loadItems()
    }

    // MARK: - Table view data source
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return itemArray.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: Constants.cellIdentifier, for: indexPath) as! Cell
        let array = itemArray[indexPath.row]
        cell.dateCreated.text = array.dateCreated
        cell.workoutLabel.text = array.workoutName
        cell.weightLifted.text = array.weight
        return cell
    }

//MARK: - Add Button Pressed
    @IBAction func addItemPressed(_ sender: UIBarButtonItem) {
        let storyboard = UIStoryboard(name: "AddItem", bundle: nil)
        let addItemVC = storyboard.instantiateViewController(identifier: "AddItemController")
        addItemVC.isModalInPresentation = true
        addItemVC.modalPresentationStyle = .overCurrentContext
        addItemVC.modalTransitionStyle = .crossDissolve
        addItemVC.navigationController?.isNavigationBarHidden = true
        present(addItemVC, animated: true, completion: nil)
    }
    
    
    
    
    
    
//MARK: - Create and Load Functions
    func saveData() {
        do {
            try context.save()
        } catch {
            print("Error Saving Data \(error)")
        }
        tableView.reloadData()
    }
    func loadItems() {
        let request: NSFetchRequest<Item> = Item.fetchRequest()
           do {
           itemArray = try context.fetch(request)
           } catch {
               print("error")
           }
        tableView.reloadData()
    }
}

//MARK:// - Add Item Vc Delegate
extension TableViewController: reloadTableView {
    func reloadTableView() {
        do {
            try context.save()
        } catch {
            print("Error Saving Data \(error)")
        }
        let request: NSFetchRequest<Item> = Item.fetchRequest()
           do {
           itemArray = try context.fetch(request)
           } catch {
               print("error")
        }
        tableView.reloadData()
        print("There are", itemArray.count, "in the item array")
        print(itemArray.last?.workoutName)
          //the print statement are not showing up in console
    }
}

and the second file和第二个文件


import UIKit
import CoreData

class AddItemController: UIViewController {
    
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    var delegate: reloadTableView?
    
    @IBOutlet weak var viewContainer: UIView!
    @IBOutlet weak var exercise: UITextField!
    @IBOutlet weak var weight: UITextField!
    @IBOutlet weak var reps: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    @IBAction func addMaxPressed(_ sender: UIButton) {
        if exercise.text != "" &&  weight.text != "" &&  reps.text != "" {
            let newItem = Item(context: context)
            let formatter = DateFormatter()
            newItem.dateCreated = formatter.formattedDate()
            newItem.weight = weight.text
            newItem.reps = reps.text
            newItem.workoutName = exercise.text
            dismiss(animated: true) {
                self.delegate?.reloadTableView()
            }
        }
    }
    @IBAction func exitPressed(_ sender: UIButton) {
        dismiss(animated: true, completion: nil)
    }
}

//MARK: - UITextField func
extension AddItemController: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.view.endEditing(true)
        return true
    }
}

You're setting the delegate on the wrong instance of the add item view controller.您在添加项视图控制器的错误实例上设置委托。 You create one instance with...您创建一个实例...

let addItemVC = AddItemController()

...and another with... ……还有一个……

let addItemVC = storyboard.instantiateViewController(identifier: "AddItemController")

You set the delegate on the first of those, but present the second.您将委托设置为第一个,但呈现第二个。 That means when you get to...这意味着当你到达...

self.delegate?.reloadTableView()

...of the presented controller, nothing happens. ...在所呈现的控制器中,什么也没有发生。

If you're not using the first instance, get rid of it and set the delegate in the same section where you set the presentation style, etc.如果您不使用第一个实例,请删除它并在设置演示文稿样式等的同一部分中设置委托。

When you put ??时候放? after an optional, it means you don't want to know whether it did what you asked or not.在可选之后,这意味着您不想知道它是否按照您的要求执行。 Obviously, you do want to know so you should test the value instead and print a message if the value isn't what you expect.显然,您确实想知道,因此您应该测试该值,如果该值不是您所期望的,则打印一条消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM