Skip to Content
Course content

73: NotificationCenter for Event Broadcasting

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Listen, I see this all the time when developers first encounter NotificationCenter: they start treating it like a "magic glue" that can replace delegates, closures, and direct references. They think, "Why bother passing a delegate from the View Controller to the Service class when I can just fire a notification from anywhere and have anyone listen for it?"

"It's just a more flexible Delegate pattern"

If you use NotificationCenter as a replacement for one-to-one communication, you're setting a trap for yourself. Imagine you have a PaymentProcessor class and a CheckoutViewController. If the processor sends a .paymentDidComplete notification, and the checkout view listens for it, it looks clean at first. But as your app grows, you'll find yourself staring at a bug where a payment completes, but you have no idea who is actually handling the response or why three different unrelated classes are suddenly triggering side effects. You've traded a clear, traceable line of communication for a "shout into the void" architecture. It makes debugging a nightmare because you can't just Command-Click on a method to see who is calling it.

Broadcasting to a Crowd vs. Talking to a Person

The correct mental model is broadcasting. Use NotificationCenter when one event needs to notify an unknown number of observers who don't necessarily have a direct relationship with the sender.

Think of a music app. When a song starts playing, several unrelated parts of the UI need to react: the "Now Playing" bar at the bottom of the screen needs to animate, the "Playlist" view needs to highlight the current track, and perhaps a "Lyrics" view needs to start scrolling. The AudioEngine shouldn't need a reference to three different view controllers just to tell them the song changed. It just shouts, "Hey, the song changed!" and whoever cares handles it.

// First, always extend Notification.Name to avoid typos and "stringly-typed" code
extension Notification.Name {
    static let didChangeSong = Notification.Name("didChangeSong")
}

class AudioEngine {
    func playSong(_ song: Song) {
        // ... logic to play music ...
        
        // We broadcast the event and pass the song object in the userInfo dictionary
        NotificationCenter.default.post(
            name: .didChangeSong, 
            object: nil, 
            userInfo: ["song": song]
        )
    }
}

Wiring Up Your Observers

Now, on the receiving end, you need to tell the system that you're listening. I usually recommend doing this in viewDidLoad or an initializer. You provide a selector—a function that will execute whenever that specific notification name is broadcast.

class NowPlayingBar: UIView {
    init() {
        super.init(frame: .zero)
        
        NotificationCenter.default.addObserver(
            self, 
            selector: #selector(handleSongChange(_:)), 
            name: .didChangeSong, 
            object: nil
        )
    }

    @objc func handleSongChange(_ notification: Notification) {
        // Extract the data from the userInfo dictionary
        if let song = notification.userInfo?["song"] as? Song {
            print("Updating UI for song: \(song.title)")
        }
    }
    
    required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
}

Cleaning Up the Noise

One thing that trips people up—especially in older versions of Swift/iOS—is memory leaks. While modern iOS handles some of the cleanup for you, it is still a professional best practice to remove your observers when the object is being destroyed. If you don't, you might end up with "ghost" observers trying to call methods on objects that no longer exist, leading to crashes or weird behavior.

I always add this to the deinit of any class that registers for notifications:

deinit {
    NotificationCenter.default.removeObserver(self)
}



📋 Practical Task

Implementing a Global Theme Switcher with NotificationCenter

Your goal is to create a system where a user can toggle between "Light Mode" and "Dark Mode," and multiple unrelated views update their appearance instantly.

Requirements:

  • Create a Notification.Name extension called themeDidChange.
  • Create a ThemeManager class with a function toggleTheme(). This function should flip a boolean isDarkMode and post the themeDidChange notification, passing the current theme state (true/false) in the userInfo dictionary.
  • Create two different classes (e.g., HeaderView and SettingsView) that both observe themeDidChange.
  • In the observer method of both views, print a message to the console: "[ClassName] switched to [Dark/Light] mode".
  • Ensure both views properly remove themselves as observers in their deinit methods.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.