===============Item==================
#import <Foundation/Foundation.h>
@interface Item : NSObject
@property (nonatomic,strong)NSString*name;
@property (nonatomic,assign)double price;
@end
#import "Item.h"
@implementation Item
@synthesize name,price;
@end
===============ItemView==================
#import <Foundation/Foundation.h>
@classItem;
@interface ItemView : NSObject
@property (nonatomic,strong) Item*item;
-(void)showItemInfo;
@end
#import "ItemView.h"
#import "Item.h"
@implementation ItemView
@synthesize item=_item;
-(void)showItemInfo{
NSLog(@"name=%@,price=%f",_item.name,_item.price);
}
-(void)setItem:(Item *)item{
self->_item = item;
//Add a monitor to the item to monitor the change of the item's name attribute
[self.item addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];
//Add a monitor to the item to monitor the change of the item's price attribute
[self.item addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionNew context:nil];
}
//Override the method, when the monitored data model changes, the listener's method will be called back
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
NSLog ( @"===observeValueForKeyPath method called ===" );
NSLog ( @"The modified keyPath is:%@" ,keyPath);
NSLog ( @"The modified object is:%@" ,object);
NSLog ( @"The value of the property being modified: %@" ,[change objectForKey: @"new" ]);
NSLog ( @"Modified am:%@" ,context);
}
-(void)dealloc{
[self.item removeObserver:self forKeyPath:@"name"];
[self.item removeObserver:self forKeyPath:@"price"];
}
@end
===============main==================
#import <Foundation/Foundation.h>
#import "ItemView.h"
#import "Item.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Item * item = [[ Item alloc ] init ]; //Modify properties
//Set item property
item.name = @"IOS";
item.price = 109;
ItemView * itemView = [[ItemView alloc]init];
[itemView setItem:item];
[itemView showItemInfo];
item.name = @"JAVA";
item.price = 888;
}
return0;
}