1

Ok so i have been trying to figure out how to do this for a while but i did not seem to find way to do it. Also i would like the proper way to do this.

A server that i have is sending notifications every 30 seconds to my device. Lets say i am in ViewController B, but the data that is received by the notification is ment to be displayed/used in ViewController A.

Lets say i received two notifications while i was in ViewController B. Then i navigate to ViewController A. How would i get it to display the most recent data that was received by the notification?

Nitish
  • 13,845
  • 28
  • 135
  • 263
Timo Cengiz
  • 3,367
  • 4
  • 23
  • 45

1 Answers1

2

You should receive the notification in a (global) 3rd object that will store them, then when the VC A is displayed you'll easily retrive them from that object... Follow the "shared instance" path used by many iOS classes (even if someone don't like it 'cause they read singletons are evil, I think this's the perfect case to use it).

You can solve it this way:

  1. Create at startup your singleton class that will receive the notifications and keep them in a queue.
  2. Add to the singleton methods to read/consume the notification queue.
  3. From any class you need the data (i.e. your view controller) get the infos you need via the methods above.

This solution keep data manager (notification handling) and presentation (the view controller) separated, I don't see any real cons...

Again, I know singletons have a bad reputation (and often people abuse of this pattern) but you know Apple's NSNotificationCenter have a +defaultCenter class method that return the shared instance (another word for singleton) so I'm quite sure this's the case to use it.

here http://www.daveoncode.com/2011/12/19/fundamental-ios-design-patterns-sharedinstance-singleton-objective-c/ you can find a good example how to implement the +sharedInstance (or +defaultCenter or whatever you want to call it) method.

Hope this help.

  • http://stackoverflow.com/questions/569940/whats-the-best-way-to-communicate-between-view-controllers I read from here that you should NOT use singleton classes – Timo Cengiz Feb 04 '15 at 14:10
  • Would you mind posting some code of how that would look? – Timo Cengiz Feb 04 '15 at 14:18
  • I don't want to start a religion war pro/con singletons, but to me this's exactly the case for use it: you get (external) notifications and you need an object to handle them that MUST be different from your VC. The singleton will handle them and the VC that need infos ask for them. – il Malvagio Dottor Prosciutto Feb 04 '15 at 21:34