Sunday, January 3, 2010

C++ Observers in Objective C

Cello has various notifications that are posted to observers. This is a good and fine thing - the observers are generally UI components and in the PC version of Cello are C++ classes. The form is that through multiple inheritance of a mix-in class a class becomes an observer. It overrides the observation methods and handles the notifications. The rub comes with Objective-C.

Under OSX all the UI components are Objective C classes these can not inherit (neither multiply nor singly) from a C++ class - yet they need to be observers. So how to solve the problem? There seem to be two possibilities:
  1. Get the Objective C classes to "somehow" observe.
  2. Reroute all messages through the NSNotification system.
I have chosen the first option. Why? Well I want to use as much of the original code as possible and I don't want to have to serialize all the information that is passed to the observer as Objective C objects.

So how to do it? The method I chose is fairly simple. It goes like this:
  • For each observer write an equivalent protocol to the virtual method(s) in the C++ mix-in class.
  • Write a C++ class that is a subclass of the C++ mix-in observer and forwards the observations to an Objective C object that conforms to the protocol.
  • Now write your Objective-C class. It should conform to the protocol. It also has a member that is a pointer to the forward class that it owns (creates and destroys) and forwards the messages.
It is a modest fiddle - but works well.

No comments: