7.3. Defining the names (identifiers) of the Notifications in a Better Way
In real life, the Notification Center is used very frequently, especially when we fetch data from the internet and wait for data to update. Oftentimes, it's pretty common to create tens of observers in a single app. So, just writing the names/identifiers of the notifications, as we did before, is not a good way of dealing with it. If the names do not match on both sides, notifications won't work. So, keeping the names in a separate class as static variables is better.
So, let's create a new Swift file (not a Cocoa touch class) called NotificationNames.swift.

Write the following code inside it:
Here we are extending Notification.Name class, and defining new static names inside it. We used only one observer with the identity/name "textFromSecondScreen." textFromSecondScreen static constant is holding that identifier. So, now we will update the addObserver() and post() methods as follows:
addObserver() method:
Previously we had:
We can now write:
post() method:
Previously we had:
Now we can write:
This way, we can easily store multiple identifiers/names without worrying about fogetting and mismatching them.
Last updated
Was this helpful?