Search code examples
appendswift4.1

How do I append values to a dictionary from another viewcontroller in a macos application?


I am recently working on an application which contains data stored in a dictionary. This data is then stored in a table which the user can view. This is how the data is stored:

Bill(Date: "4/28/18", Item: "something", Amount: 43.67)

I want to append data from a secondary view controller and the way I am currently trying to use is this:

ViewController().bills.append(Bill(Date: valueDate, Item: valueItem, Amount: Double(valueAmount)!))

The variables are all preset and work fine when I print them out and when I run this code in the initial view controller it works perfectly, but when I run the code above in the second view controller, no errors come up but it does not seem to append the data at all.

This is on Swift 4.1 Xcode 9.4.1


Solution

  • All I can understand from the stated issue is you have your "bills" array in First ViewController and you are appending the Bill object in Second View Controller. The issue in your code is that you are creating a new instance for First View controller in your second viewController, hence you can access "bills" array but issue is that the new instance and your original First View controller is different.

    You can achieve this by :- 1. Using delegates (You can follow this link :- https://medium.com/@jamesrochabrun/implementing-delegates-in-swift-step-by-step-d3211cbac3ef).
    2. Using Notifications :- Post notification from your second View controller :-

    NotificationCenter.default.post(name: NSNotification.Name(rawValue:"NotificationName"), object: nil, userInfo: ["bill":Bill(Date: valueDate, Item: valueItem, Amount: Double(valueAmount)!)])
    

    here NotificationName could be any string, and pass your object Bill in user info

    And then remove and add observers in first View controller in ViewDidLoad:-

    NotificationCenter.default.removeObserver(self, name:NSNotification.Name(rawValue:"NotificationName") , object: nil)
     NotificationCenter.default.addObserver(self, selector: #selector(self.changeTintColor(notification:)), name: NSNotification.Name(rawValue: "NotificationName"), object: nil)
    
    func getData(notification: NSNotification){
    let Bill = notification.userInfo!["bill"]
     // do your task here
    }