[英]How to save data from another view controller and reload tableview?
I'm making an expense tracking app.我正在制作一个费用跟踪应用程序。 I have added a table view in the main view controller, and added an "add" button in the navigation controller.
我在主视图 controller 中添加了一个表格视图,并在导航 controller 中添加了一个“添加”按钮。 On clicking this, it shows a view controller in which you type in the data.
单击它时,它会显示一个视图 controller,您可以在其中键入数据。 On clicking add at the end, it should save the entered data through coreData, and then be presented in the tableView, but my app crashes saying that a nil value was found, even though I have integrated the "??"
在最后点击添加时,它应该通过coreData保存输入的数据,然后在tableView中呈现,但是我的应用程序崩溃说找到了一个nil值,即使我已经集成了“??” safe guard.
安全卫士。
"
"
You tableview in startingViewController is nil this is the problem.您在startingViewController 中的tableview 为零,这就是问题所在。 When you call the MainVC.getAllItems() your tabview is not initialized.
当您调用 MainVC.getAllItems() 您的 tabview 未初始化。 Probably you are re creating startingViewController on your second controller to reach it getAllItems function but it is a wrong approach.
可能您正在第二个 controller 上创建 startingViewController 以达到它 getAllItems function 但这是一种错误的方法。 You need to update previous viewController datas with protocols or notifications.
您需要使用协议或通知更新以前的 viewController 数据。
First you need to create a protocol like below首先,您需要创建一个如下所示的协议
protocol AddViewControllerDelegate {
func updateTableView()
}
After that you need to define a variable in your addViewcontroller with this protocol type and call protocol's function when user adds new expense.之后,您需要在 addViewcontroller 中使用此协议类型定义一个变量,并在用户添加新费用时调用协议的 function。
class AddViewController: UIViewController {
var delegate: AddViewControllerDelegate?
func callUpdateTableView() {
delegate?.updateTableView()
}
}
In your StartingViewController must conform this protocol.在您的 StartingViewController 中必须符合此协议。 So you need to add updateTableView function.
所以需要添加updateTableView function。 Also you need to say the delegate of your second class is your first class in where you show your addViewController.
您还需要说您的第二个 class 的代表是您的第一个 class,在您显示 addViewController 的位置。
class StartingViewController: UIViewController, AddViewControllerDelegate {
func goToAddViewController() {
let vc = AddViewController()
vc.delegate = self
show(vc, sender: nil)
}
func updateTableView() {
// Reload Tableview
}
}
So basically, when you call the protocol function from your secondViewController, your firstViewController's updateTableView function called and you can reload your tableview in this function.所以基本上,当你从你的 secondViewController 调用协议 function 时,你的 firstViewController 的 updateTableView function 被调用,你可以在这个 ZC1C425268E68385D1AB5074C149A 中重新加载你的 tableview。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.