Wertever
Wertever

Reputation: 45

Passing data between View Controllers with NSNotificationCenter

everyone. I wrote this code to pass data between VCs but I'm not sure why it's not working.

Here's the code in ViewController1:-

import UIKit
import Foundation

let foodDict: [String:String] = [
    "Orange": "Fruit",
    "Carrot": "Vegetable",
    "Pear": "Fruit",
    "Spinach": "Vegetable"
]

class ViewController1: UIViewController {

     override func viewDidLoad() {
         super.viewDidLoad()

         NSNotificationCenter.defaultCenter().postNotificationName("SEND_STRING", object: nil, userInfo: foodDict)

     }
 }

In ViewController2:-

import UIKit
import Foundation

class ViewController2: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "printStringDict:", name: "SEND_STRING", object: nil)
    }

    func printStringDict(notification: NSNotification) {

        print("Got the notification...")
        let foodDictFromVC1 = notification.userInfo as! [String:String]
        print(foodDictFromVC1)
    }

}

VC2 doesn't get the dictionary (since nothing prints). Can someone help? Thanks in advance.

Upvotes: 1

Views: 865

Answers (2)

user5675936
user5675936

Reputation:

So problem is that you post notification but your VC2 is not initialised yet so no-one can get this post that you have in view did load in VC1. It is better to use prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) function to communicate between two ViewControllers connected with segue for e.g.:

import UIKit
import Foundation



class ViewController1: UIViewController {

    let foodDict: [String:String] = [
        "Orange": "Fruit",
        "Carrot": "Vegetable",
        "Pear": "Fruit",
        "Spinach": "Vegetable"
    ]
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "segueIdentifierSetInStoryboard" {
            if let destinationVC = segue.destinationViewController as? ViewController2{
                destinationVC.printStringDict(foodDict)
            }
        }
    }
}

class ViewController2: UIViewController {       
    func printStringDict(fooDict:[String:String]) {
        print(fooDict)
    }
}

Upvotes: 1

hla
hla

Reputation: 258

If I understand : ViewController1 -> ViewController2

In that case, your code will never work because, in ViewController1 you post a notification but nothing is listening to your notification because ViewController2 hasn't been created yet !

In ViewController2, you add an observer that listen to any notification that fit a name "SEND_STRING". To make notification works, you have to add an observer on ViewController1 and then trigger a post notification on ViewController2! => ViewController1 will be notified !

Upvotes: 0

Related Questions