vc-supplement and examples ">KVC supplement and example how to get values and modify values-–>how
- (void)setValue:(id)value forKey:(NSString *)key - (id)valueForKey:(NSString *)key - (id)valueForKey:(NSString *)key //以 key 作为标示符,获取其对应的属性值 - (void)setValue:(id)value forKey:(NSString *)key //以 key 作为标示符设置其对应的属性值 - (id)valueForUndefinedKey:(NSString *)key - (void)setNilValueForKey:(NSString *)key ``` Demo 创建一个QYPerson 类继承于 NSObject QYPerson.h ``` #import @interface QYPerson : NSObject@property (nonatomic, strong) NSString *name;@property (nonatomic, assign) int age;- (void)changeName;@end
Implement the above method in the Qyperson.m file
#import QYPerson.h@implementation QYPerson- (void)changeName{ _name = @changeName;}@end
Create a Qypersonmonitor class to monitor the name property in Qyperson to implement monitoring of the Name property in the. m file for Qyperson
#import QYPersonMonitor.h@implementation QYPersonMonitor// 2. 回调的方法 当观察的值改变的时候,该方法会被调用- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ if ([keyPath isEqual:@name]) { NSLog(@change name: old :%@, new : %@,[change objectForKey:NSKeyValueChangeOldKey],[change objectForKey:NSKeyValueChangeNewKey]); }}@end
Initializing monitored objects and monitored objects in the controller, registering the viewer
#import viewcontroller.h#import qyperson.h#import qypersonmonitor.h@interface ViewController () @ Property (Nonatomic, Strong) Qyperson *person; @end @implementation viewcontroller-(void) viewdidload {[Super Viewdidloa D]; Initialize the object being monitored _person = [[Qyperson alloc] init]; _person.name = @zhangsan; _person.age = 18; Monitoring object Qypersonmonitor *personmonitor = [[Qypersonmonitor alloc] init]; 1. Registered an observer [_person addobserver:personmonitor Forkeypath: @name options:nskeyvalueobservingoptionnew| Nskeyvalueobservingoptionold Context:nil]; Initializes the value NSLog (@person ' s name is%@,_person.name); With the SetValue method, the Qypersonmonitor monitoring will be invoked [_person setvalue:@ (Lisi by KVC) Forkey: @name]; Print the value modified by KVC mode NSLog (@person ' s name get by KVC is%@,[_person Valueforkey: @name]); The effects of the. Syntax modification are consistent through SetValue _person.name = @name change by. Name= Wangwu; Change the Name property by the person's own function [_person changename];} @end
Lan Yi IOS KVC Supplements and examples