mercredi 25 mars 2015

Observer, Notification, Delegate swift ios8

I'm looking for some advice as how to best implement something which I think might be an observer, might be a multicast delegate or perhaps i'll just use notification enter.


I'm creating a DataManager class that connects to various data sources and produces a common data format.


Example:


We can generate a LocationMessage from either Internal Core Location, File Playback, Network Socket provided location, etc.


The data type returned is a LocationMessage that has a common format, which can also be converted into a CLLocation if necessary.


In my current "multi-delegate" model if you want to get location updates you have to implement the LocationConsumer protocol which defines



func didUpdateLocation(newLocation: LocationMessage)
{
println("\(__FUNCTION__) \(newLocation)")
}


Then you would



//Instantiate a data manager
let dm : DataManager = DataManager()

//Register yourself as a delegate
dm.addLocationDelegate(self)


Internally when we get new location data the following is called:



let closure = {
(delegate : LocationDataConsumer) -> () in
dispatch_async(self.delegateQueue) {
delegate.didUpdateLocation(parsedLocation)
}
}
locationDelegates.map(closure)


where locationDelegates is an array of [LocationConsumer]


Discussion


So, first off this obviously isn't really following a delegate pattern because you aren't supposed to have multiple delegates.


What I really like about the current approach, however, is it seems very clean to use a protocol in order to identify a class as caring about a specific data type. What I'm uncomfortable with, however, is "breaking" the standard delegate pattern.


From doing some reading I think the most appropriate approach would be to use a Notification Pattern, however, I feel from a coding point of view there is more maintenance involved (although I could be wrong). The simplicity of just implementing the protocol with this delegate method and calling addDelegate is lost with Notifications. I assume I have to specifically register for each notification i care about - correct?


I could not do something like:



class notificaitonClass : LocationNotifiee, WeatherNotifiee {


}


So I guess my question is



  • 1: Have I implemented an Observer Pattern

  • 2: What are the downsides of my current approach

  • 3: Is there a way to define a swift protocol which will cause the class that implements it to automatically subscribe to a set of notifications

  • 4: What would be a better approach ?


(Hope this isn't too vague)


Aucun commentaire:

Enregistrer un commentaire