Search code examples
swiftsingletonprotocolsdelegation

Swift Delegate set on a singleton at 2 places


I have a singleton called GameCenterFacade. In my app homepage ViewController I set:

GameCenterFacade.shared.delegate = self

I then use the same code in an custom class that is an instance variable of the homepage ViewController. This seems to update the GameCenterFacades' shared delegate to be the Instance variable rather than the ViewController. As a result the protocol method only gets called in the custom class and not the ViewController.

Is there a clever way round this where you can set both the View Controller and the Instance Variable custom class as the GameCenterFacade's singleton delegate? I guess because it is a singleton it can have only 1 delegate?


Solution

  • The delegate design pattern is a to-one pattern. Any given object only has one delegate.

    That said, it wouldn't be that hard to create your own multi-delegate pattern. Give the object that you want to have several delegates (multiDelegates, let's call them) an array of delegate objects. Have its init method create an empty array multiDelegates.

    Give the object that manages a multiDelegate array an addDelegate method and a removeDelegate method. in fact, create a MultiDelegateProtocol that defines these methods.

    In the GameCenterFacade, when it goes to notify clients about interesting events, have it loop through it's array of multiDelegates and notify each one in turn.

    Alternately, you could use a publish/subscribe pattern, or Notification Center.