Swift 4 property observers: responding to changes in property values and managing state

Swift tutorials by iosbrain.comWe’re going to learn about a feature of Swift called “property observers” that help developers manage app state. You can easily add code to monitor changes to Swift native type property values as well as your own custom type property values. Remember that you can gain insight into an application by looking at its state: the data values stored in all properties of the app at a specific point in time. Getting a grip on app state, therefore managing complexity, is one of the biggest challenges in computer science. Property observers are one technology that help you get a grip. In today’s article, I’ll explain this Swift feature, demonstrate its usage with runnable examples of Swift code, show you how I built an app which relies on property observers, and provide you a list of other Swift technologies that help you manage app state and complexity. Here’s my sample app in action:

Download the Xcode 9 project and playground, both written in Swift 4, from GitHub so you can follow along with my discussion.

Continue reading “Swift 4 property observers: responding to changes in property values and managing state”

NSNotificationCenter in Swift 4: Intra-app communication, sending, receiving, listening, stop listening for messages

[Download Xcode 9 project with full Swift 4 source from GitHub.]

The topic today is how to communicate between objects within an app, specifically using iOS’s NSNotificationCenter. In the last post, “Tutorial: delegates and delegation in Swift 4,” I used delegation to communicate between two objects. In the code I wrote for the last article, the app’s main (and only) view controller waited to display an image. The image was not included in the app bundle, rather downloaded from a NASA website. I created a class that downloaded the image file. The view controller was informed that the image was finished downloading and ready to display using a technique called “delegation.” Here, we’ll modify the delegation tutorial code to work with NSNotificationCenter instead. The image downloading class will notify the view controller that the image has finished downloading by sending a notification (message).

I will show you: 1) a one-post-to-one-observer notification; and, 2) a broadcast, where one post is received by many observers. Download the project and follow along in Xcode. Here’s the app we’ll build:

Continue reading “NSNotificationCenter in Swift 4: Intra-app communication, sending, receiving, listening, stop listening for messages”