KVC : key value code 键值编码: 间接给属性赋值(系统属性,自定义属性都可以)
KVO:key value observing 键值观察者 , 是用来观察属性值变化的,不仅可以观察自定义类的属性,也可以观察系统的属性值变化
下面就用代码看看:
新建两个类,Person和Student
//Student
#import <Foundation/Foundation.h>
@interface Student : NSObject
@property (nonatomic ,copy)NSString *stuName; /**< 姓名 */
@property (nonatomic, assign)NSInteger stuAge; /**< 年龄 */
@end
//Person:
#import <Foundation/Foundation.h>
#import "Student.h"
@interface Person : NSObject
@property (nonatomic ,copy)NSString *name; /**< Pesson姓名 */
@property (nonatomic, assign)NSInteger age; /**< 年龄 */
@property (nonatomic, retain)Student *stu; /**< 学生对象 */
@end
在viewController里引入Person头文件
#import "Person.h"
- (void)viewDidLoad {
[super viewDidLoad];
//[self.view setValue:[UIColor redColor] forKey:@"backgroundColor"];
//有些属性是只读的,直接self.不可以,但是KVC就可以.
self.person = [[Person alloc] init];
[self.person setValue:@"林翰" forKey:@"name"];
NSLog(@"name = %@", self.person.name);
//根据路径给属性赋值
[self.person setValue:@"23" forKeyPath:@"age"];
NSLog(@"age = %ld", self.person.age);
//给属性的属性赋值
[self.person setValue:@"马强" forKeyPath:@"stu.stuName"];
NSLog(@"stuName = %@", self.person.stu.stuName);
//KVO
//注册当前类为观察者,观察Person类属性的变化
//参数1:设置观察者为self
//参数2:设置观察属性
//参数3:观察值的状态
//参数4:设置观察内容
[self.person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:@"观察Person的name值"];
}
//当属性值发送变化时触发的方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
NSLog(@"keyPath = %@", keyPath);
NSLog(@"object = %@", object);
NSLog(@"change = %@", change);
NSLog(@"context = %@", context);
NSLog(@"self.person.name = %@", self.person.name);
}
- (IBAction)kvoBtn:(UIButton *)sender {
[self.person setValue:@"Lisa" forKey:@"name"];
}