Dog类.h:
@interface Dog : NSObject{
NSString *dogName;
}
Person类.h:
#import "Dog.h"
@interface Person : NSObject{
NSString *name;
int age;
Dog *dg;
}
Person *xiaowang = [[Person alloc]init];
//使用KVC设置变量的值
//使用之前必须知道变量的名字
[xiaowang setValue:@"小王" forKey:@"name"];
NSString *name = [xiaowang valueForKey:@"name"];
NSLog(@"%@",name);
//对类里面的某个对象变量的实行设置
Dog *ww = [[Dog alloc]init];
[xiaowang setValue:ww forKey:@"dg"];
[xiaowang setValue:@"汪汪" forKeyPath:@"dg.dogName"];
NSString *dgName = [xiaowang valueForKeyPath:@"dg.dogName"];
NSLog(@"%@",dgName);
KVO2:
CreatedCard类.h:
@interface CreatedCard : NSObject{
int money;
}
Person类.h:
@property (nonatomic,strong)CreatedCard *card;
Person类.m:
-(void)dealloc{
[_card release];
[self removeObserver:self forKeyPath:@"card.money"];
[super dealloc];
}
-(instancetype)init{
if (self = [super init]) {
self.card = [[[CreatedCard alloc]init]autorelease] ;
//当前这个类添加一个监听器,监听card对象的money属性,监听这个属性变化之前之后的值
[self addObserver:self forKeyPath:@"card.money" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];
}
return self;
}
//属性变化之后的回调
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
int oldValue = [[change objectForKey:NSKeyValueChangeOldKey]intValue];
int newValue = [[change objectForKey:NSKeyValueChangeNewKey]intValue];
NSLog(@"old:%d",oldValue);
NSLog(@"new:%d",newValue);
}
main:
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *xw = [[[Person alloc]init]autorelease];
[xw setValue:@1000 forKeyPath:@"card.money"];
[xw setValue:@2000 forKeyPath:@"card.money"];
}
return 0;
}