Friday 16 October 2015

Key Value Coding and Key Value Observer

Key-value coding is a mechanism for accessing an object’s properties indirectly, using strings to identify properties, rather than through invocation of an accessor method or accessing them directly through instance variables.
Key-value observer is a  mechanism for observing the changes in the property of an object .

To understand these concepts properly let do some code:

1) start a new singleView iOS project and create a new class named Person .
2) In Person.h define some properties as:

@property (nonatomic, strong) NSString *name;
@property (nonatomic) NSUInteger age;
@property(nonatomic,strong) Person * person;

3)Now initialize  these property with initial values in Person.m

4) In ViewController.m , define private properties as :

@interface ViewController ()
@property(nonatomic,strong) Person * person1;
@property(nonatomic,strong) Person * person2;


@end

5)In ViewDidLoad() method, initialize the person:
    self.person1 = [[Person alloc]init];
    
    [self.person1 setValue:@"Yash" forKey:@"name"];
    [self.person1 setValue:[NSNumber numberWithInteger:25] forKey:@"age"];

    self.person1.person = [[Person alloc]init];
    [self.person1 setValue:@"rajeev" forKeyPath:@"person.name"];

That's how we have set the value of the properties using KVC .


To observe the changes in properties we have to set the observer for the object for which we are observing and implement the method observingValueForKeyPath:

6)In ViewWillAppear() method add these lines:

[self.person1 addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
[ self.person1 addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];

[self.person1 setValue:@"Jeet" forKey:@"name"];
[self.person1 setValue:@"rajeev" forKey:@"name"];

Here we set the observer self(ViewController), and make some change to the name property of the Person  

7) Now implement the method that will be called as changes occurs in the Person's properties .

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    
   if ([keyPath isEqualToString:@"name"]) {
            NSLog(@"the name of person is changed");
            NSLog(@"%@",change);
        }
   if ([keyPath isEqualToString:@"age"]) {
        NSLog(@"the age of person is changed");
        NSLog(@"%@", change);
     }
}

Here we just print the change to the console . We can handle the changes as per our requirements .

    
    

    


No comments:

Post a Comment