简体   繁体   中英

How to use the data from a notification that is meant to be used in VC A , when i am in VC B

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?

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM