Free songs

Single blog// see post details

Design Patterns: KVO

KVO can be a very powerful and useful design pattern. Here, we’ll discuss how to make it work.

First of all, you’ll want to create an observer to listen for any key posts. Here’s how you add an observer:

[[NSNotificationCenter defaultCenter] addObserver:self

Let’s go over this method.

  • The first message to the method is addObserver. It takes the class that will be watching as an argument.

  • Next is selector. You’ll want to send a selector to the method that should be called after the event is fired.

  • Name is the next message in the method. Name is the string being sent, or the key value.

  • Finally, if you’re not sending any extra information to the notification, object should be nil.
  • Now that we’ve added an observer, we want to post the notification. Here’s the code to do that:

      [[NSNotificationCenter defaultCenter] postNotificationName:keyValue object:self];


  • The first message is the string being used as the key value. I usually set this as a constant and use the same name in both the observer and the post

  • Next is the object being sent. This should usually be self.

    Finally, we can’t forget to remove the observer in dealloc. Here’s the code to remove it:

      [[NSNotificationCenter defaultCenter] removeObserver:keyValue];

    That’s all there is to it. It’s pretty simple once all is said and done.

    Leave a Reply

    Your email address will not be published. Required fields are marked *