I’m stuck with a problem now and I need some help.
Currently, I have two different view controllers in my project, VC1 and VC2. In the project, I have both a navigation bar and a tab bar.
In the VC1, I have a UIViewController class and it contains a UITableView and the tablaViewCell. Also, I add an array of liveEvents like below.
public var liveEvents: [LiveEvent] = [
LiveEvent(title: "aaaa"),
LiveEvent(title: "bbbbbb"),
LiveEvent(title: "ccccccc")
]
Then, from the cell, I added the segue to the VC2. In the VC2, I added the IBaction to barbutton item like below.
@IBOutlet weak var eventTitle: UITextField!
@IBAction func saveNewLiveEvent(_ sender: Any) {
if let eventTitle = eventTitle.text {
let vc = VC1()
vc.liveEvents.append(LiveEvent(title: eventTitle))
print("liveEvent: (vc.liveEvents)")
navigationController?.popViewController(animated: true)
}
}
and I tried to append an event in the liveEvent array in the VC1.
In the console, I can see the new event is appended in VC2, however, when I add the print statement in the VC1, I don’t see the new added value is appended (also, the new value is not reflected on the table view.) when I back from VC2 to VC1.
I was wondering how to append the value to an array which is in the different swift file.
If you know what I’m doing wrong, please let me know.
2
Answers
You created a new instance of
VC1
inVC2
, it’s not the same instance you pushed from. So, that’s the reason your table isn’t updating.You can use
delegation
approach to achieve your result. I have created a demo code for this, please check below.TestController1 (or VC1)-
TestController2 (or VC2)-
CustomCellClass-:
The
Storyboard
design is simple, I just have TableView with singlecell
, having alabel
in it.I have connected segue in storyboard itself from
cell
toVC2
for demo purpose.Here is a solution for you. In short, you cannot create new instance of
VC1
as you did inVC2
. You need existing instance which can be achieve usingprotocol
approach. Check the code. This will fix you issue.