I am developing a chat application, where i have multiple view controller classes. I also have a generic class where communication is happening between server and client. This communication class never know which view controller is been accessed it, because it is been accessed by all the view controllers for different reasons. In this situation, I am in need of updating the states like ‘connection failed’, ‘internet failure’, ‘data failed’, ‘chat communication failed’ like that to all the view controllers as soon as such errors happening at the communication class. I am thinking to solve by this having a flag setting in a singleton class and access it anywhere else (or) have a protocol (which is very secured than singleton) and set the status flag in communication class, and other view controllers can implement this protocol method to know the current status.
Could someone advise me whether i’m thinking at the right angle to implement and can achieve with these approaches?
Take a look at notifications, which are intended for general distribution to multiple instances exactly like this. See the docs for
NSNotificationCenter.Notifications are not just for hardware events, as you seem to misunderstand. They are a general purpose broadcast mechanism to distribute information, just as delegation is a general purpose mechanism to allow an individual object to manage another objects behaviour.
In other words, your communications handler should post a notification of state change, and your other controllers should all register to receive that notification, and can respond however is appropriate for them.
Post example; put this when your file has finished loading:
And in each controller that needs to update itself when loading is complete, put:
where
loadComplete:is a method that takes the notification as an argument, and does whatever you need it to do. You can pass extra data using the userInfo dictionary, which I have ignored here. Hot tip: make the notification name string a constant; I skipped this in the interest of brevity.