------------------KVC--------------
Character.h
#import <Foundation/Foundation.h>
@interface Character :
NSObject
{
NSString *Name;
NSInteger Rating;
}
@property (nonatomic, copy) NSString *Name;
@property(nonatomic, assign) NSInteger Rating;
@end
Character.m
#import "Character.h"
@implementation Character
@synthesize Name;
@synthesize Rating;
-(
void)observeValueForKeyPath:(
NSString *)keyPath ofObject:(
id)object change:(
NSDictionary *)change context:(
void *)context
{
if([keyPath
isEqualToString:
@"required"])
{
//NSLog(@"%@",[object valueForKeyPath:keyPath]);
NSLog(
@"%@",[change
objectForKey:
NSKeyValueChangeOldKey]);
}
}
@end
-(void)KVC
{
Character *conharector1;
// KVC...
conharector1 = [[Character alloc] init];
[conharector1 setValue:@"Amit" forKey:@"Name"];
[conharector1 setValue:[NSNumber numberWithInt:10] forKey:@"Rating"];
//Done!
NSString *GetconharectorName = [conharector1 valueForKey:@"Name"];
NSNumber *GetconharectorRating = [conharector1 valueForKey:@"Rating"];
NSLog(@"%@ Rating = %d ", GetconharectorName, [GetconharectorRating intValue]);
}
OUTPUT :
2013-05-16 10:58:20.263 StoryBoardApplication[536:c07] Amit Rating = 10
----------------------- KVO---------------
Employee.h
#import <Foundation/Foundation.h>
@interface Employee : NSObject
{
int required;
}
@property(nonatomic,assign) int required;
-(id)init;
@end
Employee.m
#import "Employee.h"
@implementation Employee
@synthesize required;
-(
id)init
{
self = [super init];
if(
self)
{
required =
1;
}
return self;
}
@end
Manager.h
import <Foundation/Foundation.h>
@interface Manager :
NSObject
@end
Manager.m
#import "Manager.h"
@implementation Manager
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString:@"required"])
{
//NSLog(@"%@",[object valueForKeyPath:keyPath]);
NSLog(@"%@",[change objectForKey:NSKeyValueChangeNewKey]);
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Changed" message:@"Required value has changed By Employee" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}
}
@end
Following method you can call whereever you want to :
-(void)KVO
{
Employee *employee = [[Employee alloc]init];
Manager *manager = [[Manager alloc]init];
[employee addObserver:manager forKeyPath:@"required" options:NSKeyValueObservingOptionNew context:NULL];
[employee setRequired:67];
[employee removeObserver:manager forKeyPath:@"required"];
}
OUTPUT :
2013-05-16 10:56:25.601 StoryBoardApplication[512:c07] 67
and an alert like : Required value has changed By Employee
I hope it will be help you....