KVC的使用(对一个对象的成员变量进行操作(赋值/取值))
切记:请求的数据要存在相应的类中,不能在加载试图中请求数据
KVC就是对请求数据的一个简化
MainViewController.m
#import"MainViewController.h"#import"Student.h"@interfaceMainViewController()@end@implementationMainViewController-(id)initWithNibName:(NSString*)nibNameOrNilbundle:(NSBundle*)nibBundleOrNil{self=[superinitWithNibName:nibNameOrNilbundle:nibBundleOrNil];if(self){//Custominitialization}returnself;}-(void)viewDidLoad{[superviewDidLoad];//Doanyadditionalsetupafterloadingtheview.self.view.backgroundColor=[UIColorcyanColor];//KVC的使用Student*stu=[[Studentalloc]init];//KVC的作用:对一个对象的成员变量进行操作(赋值/取值)//赋值的方法[stusetValue:@"adfasdf"forKey:@"name"];//[stusetValue:@"米4像苹果1"forKey:@"Name"];//第一个查找//[stusetValue:@"米4像苹果2"forKey:@"_Name"];//找不到//[stusetValue:@"米4像苹果3"forKey:@"_name"];////这个是一个类中的属性赋值//stusetValue:<#(id)#>forKeyPath:<#(NSString*)#>NSDictionary*dic=[NSDictionarydictionaryWithObjectsAndKeys:@"222",@"StudentID",@"liuyafang",@"name",nil];[stusetValuesForKeysWithDictionary:dic];//取值的方法NSLog(@"%@",[stuvalueForKey:@"name"]);//KVO键值观察(注册一个观察者)(自己监视自己对象的内容)//参数1:观察谁//参数2:观察哪个属性//参数3:在实现方法中获得新值合适旧值//参数4:任意的指针类型[stuaddObserver:selfforKeyPath:@"name"options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOldcontext:@"aaa"];stu.name=@"pingguo45";}-(void)observeValueForKeyPath:(NSString*)keyPathofObject:(id)objectchange:(NSDictionary*)changecontext:(void*)context{NSLog(@"%@",keyPath);NSLog(@"%@",object);NSLog(@"%@",change);NSLog(@"%@",context);}-(void)dealloc{//selfremoveObserver:<#(NSObject*)#>forKeyPath:<#(NSString*)#>[superdealloc];}-(void)didReceiveMemoryWarning{[superdidReceiveMemoryWarning];//Disposeofanyresourcesthatcanberecreated.}/*#pragmamark-Navigation//Inastoryboard-basedapplication,youwilloftenwanttodoalittlepreparationbeforenavigation-(void)prepareForSegue:(UIStoryboardSegue*)seguesender:(id)sender{//Getthenewviewcontrollerusing[seguedestinationViewController].//Passtheselectedobjecttothenewviewcontroller.}*/@end
Student.h
#import<Foundation/Foundation.h>@interfaceStudent:NSObject@property(nonatomic,retain)NSString*name;@property(nonatomic,retain)NSString*sex;@property(nonatomic,retain)NSString*studengID;//利用kvc对model进行封装-(instancetype)initWihtDictionary:(NSDictionary*)dic;@end
Student.m
#import"Student.h"@implementationStudent-(void)setValue:(id)valueforUndefinedKey:(NSString*)key{//这个方法在类的内部实现,就用就是纠错//一旦在赋值过程中,发现key没有周到对应的成员变量,就会调用这个发放//如果没有重写个方法,就会crashif([keyisEqualToString:@"id"]){_studengID=value;}}-(id)valueForUndefinedKey:(NSString*)key{//取值的纠错方法if([keyisEqualToString:@"id"]){returnself.superclass;}returnnil;}-(instancetype)initWihtDictionary:(NSDictionary*)dic{self=[superinit];if(self){[selfsetValuesForKeysWithDictionary:dic];}returnself;}-(void)dealloc{[_namerelease];[_sexrelease];[superdealloc];}@end
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。