Observer Design Pattern, Key-Value Observing

Observer Design Pattern, Key-Value Observing

Written By: Debasis Das (3-May-2015)

In the Observer Design Pattern one object notifies other objects of any state changes.

The Observer Design Pattern requires that an observer registers itself for changes in the state of another object and when the state of the other object changes, all the observing objects are notified about the change.

In Cocoa, the observer pattern is implemented in two ways

  • Notifications
  • Key-Value Observing

In this article, we will talk about the Key Value Observing (KVO) Design Pattern

In KVO , an object can register itself for notifications when a property of itself or some other object changes.

A property can be of two types

  1. An attribute (name, title, age, salary etc)
  2. Relationship to other objects

KVO uses Key Value Coding mechanism for indirectly accessing an object’s attributes and relationships using string identifiers

Following are the steps that needs to be followed for Key-Value Observing
Use the following method for adding an object as an observer for a keyPath

[self addObserver:self
               forKeyPath:@"length"
                  options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionInitial|NSKeyValueObservingOptionOld)
                  context:NULL];

Respond to changes in state of keyPath

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
}

Unsubscribe using removeObserver in the dealloc method or any other destruction method

    [self removeObserver:self forKeyPath:@"length"];

Key-Value Observing Sample Code

In the sample code we will create a simple application that represents a cuboid object, the user can change any or all of the length, breadth or height of the cuboid, the Cuboid Object observes for these properties and updates the volume property

Key-Value Observing Sample Code

Key-Value Observing Sample Code

//  Cuboid.h
//  ObjectiveC Key Value Observing
//  Created by Debasis Das on 5/4/15.
//  Copyright (c) 2015 Knowstack. All rights reserved.

#import <Foundation/Foundation.h>
@interface Cuboid : NSObject
{
    
}
@property int length;
@property int breadth;
@property int height;
@property int volume;
@end

Cuboid.m

#import "Cuboid.h"
@implementation Cuboid

-(id)init
{
    if (self = [super init])
    {
        _length = 1;
        _breadth = 1;
        _height = 1;

        //Here we are registering self for observing changes in values for keypath
        //ensure that we are removing self from observation in the dealloc method
        [self addObserver:self
               forKeyPath:@"length"
                  options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionInitial|NSKeyValueObservingOptionOld)
                  context:NULL];
        [self addObserver:self
               forKeyPath:@"breadth"
                  options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionInitial|NSKeyValueObservingOptionOld)
                  context:NULL];
        [self addObserver:self
               forKeyPath:@"height"
                  options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionInitial|NSKeyValueObservingOptionOld)
                  context:NULL];

    }
    return self;
}

-(void)dealloc{
    
    [self removeObserver:self forKeyPath:@"length"];
    [self removeObserver:self forKeyPath:@"breadth"];
    [self removeObserver:self forKeyPath:@"height"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
    
    NSLog(@"object %@",object);
    NSLog(@"change %@",change);   
    if ([keyPath isEqual:@"length"] ||
        [keyPath isEqual:@"breadth"] ||
        [keyPath isEqual:@"height"]
        )
    {
        [self setVolume:[self getRecalculatedVolume]];
    }
 }

-(int)getRecalculatedVolume{
    int volume = self.length * self.breadth * self.height;
    return volume;
}
@end

Download the code from here ObjectiveC Key Value Observing

Reference and Further Good Reads on Observer Design Pattern & Key Value Observing

Posted in Cocoa, Design Pattern, iOS, Objective C Tagged with: , , , , , , ,

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Recent Posts


Hit Counter provided by technology news