#import "ViewController.h"
#import <Foundation/Foundation.h>
@interface Datamodel:nsobject
@property (nonatomic,copy) NSString *stockname;
@property (nonatomic,assign) float price;
@end
@implementation Datamodel
@end
@interface Viewcontroller ()
@property UILabel *mylabel;
@property UIButton *mybutton;
@property Datamodel *model;
@end
@implementation Viewcontroller
-(void) Viewdidload {
[Super Viewdidload];
Self.model=[[datamodel Alloc]init];
[Self.model setvalue:@ "Searph" forkey:@ "StockName"];
[Self.model setvalue:@ "10.0" forkey:@ "Price"];
[Self.model addobserver:self forkeypath:@ "Price" options:nskeyvalueobservingoptionnew| Nskeyvalueobservingoptionold Context:nil];
Self.mylabel=[[uilabel Alloc]initwithframe:cgrectmake (130, 100, 100, 100)];
Self.mylabel.layer.maskstobounds=yes;
self.mylabel.layer.cornerradius=50;
Self.mylabel.textalignment=nstextalignmentcenter;
Self.mylabel.textcolor=[uicolor Cyancolor];
Self.mylabel.backgroundcolor=[uicolor Graycolor];
Self.mylabel.text=[nsstring stringwithformat:@ "%@", [Self.model valueforkey:@ "Price"];
[Self.view AddSubview:self.myLabel];
Self.mybutton=[uibutton Buttonwithtype:uibuttontyperoundedrect];
Self.mybutton.frame=cgrectmake (130,200, 100, 30);
[Self.mybutton settitle:@ "button" forstate:uicontrolstatenormal];
[Self.mybutton addtarget:self Action: @selector (ChangeValue) forcontrolevents:uicontroleventtouchupinside];
[Self.mybutton Setbackgroundcolor:[uicolor Lightgraycolor];
[Self.view AddSubview:self.myButton];
}
-(void) changevalue{
[Self.model setvalue:@ "20.0" forkey:@ "price"];
}
-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: (void *) context{
if ([KeyPath isequaltostring:@ "Price"]) {
Self.mylabel.text=[nsstring stringwithformat:@ "%@", [Self.model valueforkey:@ "Price"];
}
}
-(void) dealloc{
[Self.model removeobserver:self forkeypath:@ "Price"];
}
-(void) didreceivememorywarning {
[Super didreceivememorywarning];
}
@end
Easy use of IOS KVC and KVO