Adding the observer

So let's add an observer. We will create a PeopleWatcher class that holds a reference to a Person object, and will observe changes in the busy property of Person:

  1. Create a new Swift file and name it PeopleWatcher.swift.
  2. Replace the import statement with the following code:
import AppKit 

class PeopleWatcher: NSObject
{
privatevar myContext = 0
var myPerson: Person


init(person:Person)
{
self.myPerson = person
super.init()

myPerson.addObserver(self,
forKeyPath: "busy",
options: [.new],
context: &myContext)
}
}

So what's going on here?

First we create a private context variable, myContext, which we will use to identify the change notifications when they come in. The value of this variable is completely arbitrary; we will only be using its location in memory for identification. More of this shortly.

Next create an init method that takes a Person object as its argument, and retain this reference in the class's myPerson property.

In the init method, we add this PeopleWatcher instance to the Person list of observers:

  • The self argument refers to the particular PeopleWatcher instance
  • The keyPath argument, "busy", is a String representation of the name of property that we wish to observe
  • There are a number of NSKeyValueObservingOptions that we can pass in the options array, but in our case we are only interested in the new value, so we specify only the .new case of the NSKeyValueObservingOptionsenum

Then, we use &myContext to pass a pointer to the myContext object. The handler method for the notification (which we'll code next) will check this pointer to make sure this notification is our one.