Over a million developers have joined DZone.

Implementing the Presentation Model Pattern in Swift

DZone's Guide to

Implementing the Presentation Model Pattern in Swift

· Mobile Zone
Free Resource

Launching an app doesn’t need to be daunting. Whether you’re just getting started or need a refresher on mobile app testing best practices, this guide is your resource! Brought to you in partnership with Perfecto

For the last few years, almost all of the Flex projects I've worked on have used the Presentation Model (PM) pattern along with the Parsley application framework for dependency injection. 

Broadly speaking, a presentation model holds the presentational state and behavioural logic of an application and, in doing so, minimises the amount of code in view controls. Because several views can utilise the same presentation model, properties such as state can be shared between them.

Views hold a strongly typed reference to the presentation model so they can, for example, invoke methods on it. The presentation model itself has no knowledge of the views and, in the case of Flex and Parsley, it dispatches events or messages when something has changed.
For example, in a typical master-detail application, rather than the master list passing its selected item directly to the detail view when the user selects an item, it would invoke a method on its PM informing it of the change. The PM would then dispatch an event that would be picked up by the detail view to display the full record in the UI.

I thought I'd spend my time implementing a similar pattern in my recent node based UIScrollView demonstration.

The first step is to create NodesPM - in the absence of a dependency injection framework, I've cheated a little by making this struct entirely static. Because my little app only has one PM at the application level, IMHO, it's a reasonable strategy. For larger applications, a different approach may be required. 

My PM holds the application's state with the variables selectedNode and isDragging and exposes some methods for node management, createNewNode() and moveSelectedNode().

In the place of Parsley messaging, I'm using NSNotificationCentre to broadcast events. So, when a user performs a long hold gesture to create a new node, the relevant view invokes createNewNode():

1. let gestureLocation = recognizer.locationInView(self)
2.     [...]
3.     NodesPM.createNewNode(gestureLocation)

...the PM then creates a node value object and dispatches a message with that object as a payload:

01. static func createNewNode(origin: CGPoint)
02.     {
03.         let newNode = NodeVO(name: "\(nodes.count)", position: origin)
05.         nodes.append(newNode)
07.         let notification = NSNotification(name: NodeNotificationTypes.NodeCreated.toRaw(), object: newNode)
09.         notificationCentre.postNotification(notification)
11.         selectedNode = newNode
13.     }

Back in the view, during initialisation I've added an observer on the PM's NodeCreated notification:

1. NodesPM.notificationCentre.addObserver(self, selector: "nodeCreated:", name: NodeNotificationTypes.NodeCreated.toRaw(), object: nil)

...so that when the view receives that event, it knows to create the relevant display object to reflect the change in the domain model:

01. func nodeCreated(value : AnyObject)
02.     {
03.         let newNode = value.object as NodeVO
05.         let originX = Int( newNode.position.x - 75 )
06.         let originY = Int( newNode.position.y - 75 )
08.         let nodeWidget = NodeWidget(frame: CGRect(x: originX, y: originY, width: 150, height: 150), node: newNode)
10.         addSubview(nodeWidget)
12.     }

The individual nodes update their colour so that the selected node is yellow and the unselected nodes are blue. This follows a similar workflow: when the user touches a node, I set the selectedNode property on the PM from the view:

1. NodesPM.selectedNode = node

...and using a didSet observer, the PM posts a notification:

01. static var selectedNode: NodeVO? = nil
02.     {
03.         didSet
04.         {
05.             if let node = selectedNode
06.             {
07.                 let notification = NSNotification(name: NodeNotificationTypes.NodeSelected.toRaw(), object: selectedNode)
09.                 notificationCentre.postNotification(notification)
10.             }
11.         }
13.     }

...and back in the widget, it compares the PM's selected node's value object with its own and updates itself accordingly:

1. func nodeSelected(value : AnyObject)
2.     {
3.         let selectedNode = value.object as NodeVO
5.         backgroundColor = selectedNode == node ? UIColor.yellowColor() : UIColor.blueColor()
6.         label.textColor = selectedNode == node ? UIColor.blackColor() : UIColor.whiteColor()
8.     }

For me, the Presentation Model pattern is quick to implement and scales up really well. This prototype version could benefit from abstracting the notification centre code and maybe a better solution that a single static PM, but I think it's a great starting point to building Swift applications with multiple view components that share a single data source.
All the source code is available in my Git Hub repository.
Stop Press!
I've changed the NodesPM to make its notificationCentre private and added a new method to simplify adding observers:

1. static func addObserver(observer: AnyObject, selector: Selector, notificationType: NodeNotificationTypes)
2.     {
3.         notificationCentre.addObserver(observer, selector: selector, name: notificationType.toRaw(), object: nil)
5.     }

Observers now don't know how notifications are implemented (so a change in implementation doesn't require any changes to views) and don't need to convert NodeNotificationTypes enumerations to their raw value. The old code, which looked like this:

1. NodesPM.notificationCentre.addObserver(self, selector: "nodeCreated:", name: NodeNotificationTypes.NodeCreated.toRaw(), object: nil)

Now looks like this:

1. NodesPM.addObserver(self, selector: "nodeCreated:", notificationType: .NodeCreated)

Additionally, I've created a helper function inside the PM to eliminate all the copied boilerplate code when posting notifications. The previous code looked like this:

1. let notification = NSNotification(name: NodeNotificationTypes.NodeCreated.toRaw(), object: newNode)
3.     notificationCentre.postNotification(notification)

...and the new code looks like this:

1. postNotification(.NodeCreated, payload: newNode)

All these changes have been pushed to my Git Hub repository.

Keep up with the latest DevTest Jargon with the latest Mobile DevTest Dictionary. Brought to you in partnership with Perfecto.


Published at DZone with permission of Simon Gladman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}