Group Group Group Group Group Group Group Group Group

Notification Center does not work properly

I have a problem with NotificationCenter in ios app.My app consists of two ViewControllers.

In the first ViewController, there are two buttons. ,Move to 2 ViewController, button makes transition to a second View Controller.

And ,Change to red color, button supposed to change color of UIView in second View Controller.

Here is code of first ViewController:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    
    @IBAction func changeToRed(_ sender: Any) {
        NotificationCenter.default.post(name: NSNotification.Name("red"), object: nil)
    }
}

Here is code of second ViewController:

import UIKit

class ViewController2: UIViewController {
    @IBOutlet weak var colorfulView: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(makeViewRed), name: Notification.Name("red"), object: nil)
    }
    
   @objc func makeViewRed() {
    colorfulView.backgroundColor = UIColor.red
    print("UIview color has been changed!")
    }
}

When, I press ,change to red color, button I see message in console that UIView color has been changed. However, when I move to second ViewController, UIView color is unchanged. How can I solve this problem?

You should probably inject the update of the second view’s color from the first view controller to the second view controller.

Using NotificationCenter to communicate between closely related ViewControllers (i.e. one arranges for the presentation of the other) is not a conventional pattern, won’t scale well and, as you have already discovered, is prone to bugs.

Look to configure the second view controller in prepareForSegue if using storyboards, or in whatever handles your “Move to 2 ViewController” action.

I suggest this course from this very site as a good starting point. (It’s the first in a series of 6 courses)

When you tap “changeToRed” and send a Notification to the second view controller, the second view controller must be fully loaded for its “addObserver” to recognize the notification that was sent from the first viewController. You are asking the second view controller to to recognize the notification before its viewDidLoad was invoked. That’s why it’s not woking. To solve the problem, use the recommendation by chrisjl.