IOS开发之KVC与KVO简述

时间:2021-03-21 19:40:33

KVC:Key-Value Coding

KVO:Key-Value Observing

Person.m

#import <Foundation/Foundation.h>

@interface Person : NSObject{
//该访问修饰符用于说明即使私有成员变量也可以通过kvc方式访问和赋值
@private
NSString *_name;
NSArray *_dogs;
}
@end @implementation Person
@end

Dog.m

#import <Foundation/Foundation.h>

@class Person;

@interface Dog : NSObject
{
@private
NSInteger _age;
Person *_owner;
}
@end @implementation Dog
@end

PersonObserve.m

#import <Foundation/Foundation.h>
#import "Person.h" @interface PersonObserve : NSObject
@end @implementation PersonObserve
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
Person *p = (Person *)object;
//使用kvc方式获取成员变量keypath的值
NSLog(@"%@",[p valueForKey:keyPath]);
}
@end

main.m

#import <Foundation/Foundation.h>
#import "Person.h"
#import "PersonObserve.h"
#import "Dog.h" int main(int argc, const char * argv[]) {
//观察者类
PersonObserve *po = [[PersonObserve alloc] init];
Person *p = [[Person alloc] init];
//使用kvo方式对成员变量“name”的属性值变化增加观察者po
//po将在该属性值发生变化时执行- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context方法
[p addObserver:po forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil]; //通过kvc方式设置成员变量“name”的属性值
//触发观察者执行对应方法
[p setValue:@"zhangsan" forKey:@"name"]; //kvc中forKeyPath的用法
Dog *d = [[Dog alloc] init];
[d setValue:p forKey:@"owner"];
[d setValue:@"lisi" forKeyPath:@"owner.name"]; //移除对私有成员变量“name”的观察
[p removeObserver:po forKeyPath:@"name"]; Dog *d1 = [[Dog alloc] init];
[d1 setValue:@ forKey:@"age"];
Dog *d2 = [[Dog alloc] init];
[d2 setValue:@ forKey:@"age"]; NSArray *array = [NSArray arrayWithObjects:d1,d2, nil];
[p setValue:array forKey:@"dogs"]; //kvc中valueForKeyPath数组内置表达式的用法
NSLog(@"dogs.age = %@",[p valueForKeyPath:@"dogs.age"]);
NSLog(@"dogs.age.sum = %@",[p valueForKeyPath:@"dogs.@sum.age"]);//dogs数组中age的总和
NSLog(@"dogs.age.avg = %@",[p valueForKeyPath:@"dogs.@avg.age"]);//dogs数组中age的平均值
NSLog(@"dogs.age.max = %@",[p valueForKeyPath:@"dogs.@max.age"]);//dogs数组中age的最大值
NSLog(@"dogs.age.min = %@",[p valueForKeyPath:@"dogs.@min.age"]);//dogs数组中age的最小值 return ;
}

结果:

-- ::34.611 KVC&KOC[:] zhangsan
-- ::34.612 KVC&KOC[:] lisi
-- ::34.613 KVC&KOC[:] dogs.age = (
, )
-- ::34.613 KVC&KOC[:] dogs.age.sum =
-- ::34.613 KVC&KOC[:] dogs.age.avg =
-- ::34.613 KVC&KOC[:] dogs.age.max =
-- ::34.613 KVC&KOC[:] dogs.age.min =
Program ended with exit code: