#import "ViewController.h"
#import "UserItem.h"
#import "WuGongItem.h"
@interface ViewController (){
UserItem* userItem;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//KVC KVO
//KVC 赋值方式 key value coding 键值编码
//KVO key value observer 键值监听
/*
[userItem setValue:@"西门吹雪" forKey:@"name"];
1.userItem里找叫做name的属性去赋值
2.如果没找到,找叫做_name的成员变量
3.还没找到,找叫做name的成员变量
4.还没找到,调userItem里的valueForUndefinedKey:方法
*/
//创建一个西门吹雪
userItem = [[UserItem alloc] init];
// userItem.name = @"西门吹雪";
//1
[userItem setValue:@"西门吹雪" forKey:@"name"];
NSLog(@"%@", [userItem valueForKey:@"name"]);
userItem.wugong = [[WuGongItem alloc] init];
//2
[userItem setValue:@"独孤九剑" forKeyPath:@"wugong.wuGongName"];
NSLog(@"%@", userItem.wugong.wuGongName);
//3
//[userItem setValuesForKeysWithDictionary:]
//KVO self监听userItem中得name
[userItem addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:NULL];
userItem.name = @"叶孤城";
}
//KVO监听的值发生变化调用
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
NSLog(@"%@",change[@"new"]);
}
//UserItem.h
#import <Foundation/Foundation.h>
#import "WuGongItem.h"
@interface UserItem : NSObject{
//NSString* name;
}
@property (nonatomic, copy) NSString* name;
@property (nonatomic, retain) WuGongItem* wugong;
@end
#import "UserItem.h"
@implementation UserItem
- (void)setValue:(id)value forUndefinedKey:(NSString *)key{
NSLog(@"%@ 不存在",key);
}
@end
#import <Foundation/Foundation.h>
@interface WuGongItem : NSObject
@property (nonatomic, copy) NSString* wuGongName;
@end
#import "WuGongItem.h"
@implementation WuGongItem
@end
@end