Search code examples
ioscode-structure

Best way to structure code


I have a UIView subclass acting as an internal "notification" system, that has a label inside that displays the notification text and animates down from the top of the view and back up. I need to create a system that will create a queue of these notifications (that can be added to from anywhere within my app), and display them one by one, but wondering how I should structure it.

Should I use a singleton that manages a queue of these UIViews? or should there be a UIViewController that has a queue? Or something else?

Thanks!


Solution

  • This is usually managed by a data persistence class. You want to separate data layer from view layer in order to maintain it properly. Implement the notification logic by creating a class that manages the notification data itself, in a queue, and just present said data in a view, in any viewcontroller that should display said notifications.

    After you create the class that manages notification data, you can either:

    1. Check inside viewDidLoad() if there is a notification in the queue. If true, present it.
    2. Create a timer and check for the queue every couple of seconds/minutes
    3. Get fancy and implement observer pattern so that every ViewController would subscribe to your notification manager class so that it notifies the VC that new data is available. When that happens, it will delegate through a protocol the presentation logic to the view controller (Preffered)

    EDIT: If you go for #3 (and you probably should), remember to use weak for the delegate, as you don't want leaked VCs