KVC(key-value coding),键值编码。指在iOS开发中,开发者可以通过属性名直接访问属性,给属性赋值或者取值,而不需要显式的调用setter和getter方法,这样就可以在运行时动态的访问和修改对象的属性。
KVC常用的四个方法
- (nullable id)valueForKey:(NSString *)key; //直接通过Key来取值
- (void)setValue:(nullable id)value forKey:(NSString *)key; //通过Key来设值
- (nullable id)valueForKeyPath:(NSString *)keyPath; //通过KeyPath来取值
- (void)setValue:(nullable id)value forKeyPath:(NSString *)keyPath; //通过KeyPath来设值
valueForKey 和 setValue: forKey:的简单用法
我们都知道当一个对象的属性在声明文件(.h)中声明时,是可以用点语法访问并赋值的,但是如果声明在实现文件(.m)中,在外面用点语法是访问不到的,此时KVC就起到作用了
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface Book : NSObject
@end
#import "Book.h"
@interface Book()
@property (strong, nonatomic) NSString *name;
@property (assign, nonatomic) CGFloat price;
@end
@implementation Book
@end
//在控制器中实现下面代码
Book *book1 = [[Book alloc]init];
[book1 setValue:@"ios" forKey:@"name"];
[book1 setValue:@12 forKey:@"price"];
NSString *name = [book1 valueForKey:@"name"];
NSNumber *price = [book1 valueForKey:@"price"];
NSLog(@"name = %@,price = %@",name,price.floatValue);
//打印结果如下
name = ios,price = 12.000000
这样以后我们自定义一些控件的时候访问私有属性就方便多了。 另外,我们还可以修改系统控件的内部属性,如我们自定义好一个tabbar,可以用下面的方式替换系统本来的UITabbar
[self setValue:[[CustomTabbar alloc]init] forKey:@"tabBar"];
valueForKeypath 和 setValue:forKeypath: 的简单用法
当一个对象成为另一个对象的属性时,使用KVC就方便的多
#import <Foundation/Foundation.h>
@class Address;
@interface People : NSObject
@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) Address *address;
@property (assign, nonatomic) NSInteger age;
@end
@interface Address : NSObject
@property (strong, nonatomic) NSString *contry;
@end
#import "People.h"
@interface People ()
@end
@implementation People
@end
@interface Address ()
@end
@implementation Address
@end
//在控制器中实现下面代码
Address *address = [[Address alloc]init];
address.contry = @"China";
People *people = [[People alloc]init];
people.address = address;
NSString *country1 = people.address.contry;
NSString *country2 = [people valueForKeyPath:@"address.contry"];
NSLog(@"1 = %@ 2 = %@",country1,country2);
[people setValue:@"中国" forKeyPath:@"address.contry"];
country1 = people.address.contry;
country2 = [people valueForKeyPath:@"address.contry"]; NSLog(@"1 = %@ 2 = %@",country1,country2);
KVC对于keyPath是搜索机制第一步就是分离key,用小数点.来分割key,然后再像普通key一样按照顺序搜索下去。
KVC 和 字典
常用的两个方法
- (NSDictionary<NSString *, id> *)dictionaryWithValuesForKeys:(NSArray<NSString *> *)keys;
- (void)setValuesForKeysWithDictionary:(NSDictionary<NSString *, id> *)keyedValues;
Addresss *add = [[Addresss alloc]init];
add.country = @"China";
add.province = @"Hebei";
add.city = @"Qinhuangdao";
add.district = @"Yanghedao";
NSArray *keys = @[@"country",@"province",@"city",@"district"];
//把对应key所有的属性全部取出来
NSDictionary *dict = [add dictionaryWithValuesForKeys:keys];
NSLog(@"dict = %@",dict);
//字典转模型
NSDictionary *modiDic = @{@"country":@"中国",@"province":@"河北省",@"city":@"秦皇岛市",@"district":@"洋河道"};
[add setValuesForKeysWithDictionary:modiDic];
NSLog(@"%@%@%@%@",add.country,add.province,add.city,add.district);
KVC处理非对象和自定义对象 (这里就不举例了!!!)
不是每一个方法都返回对象,但是valueForKey:总是返回一个id对象,如果原本的变量类型是值类型或者结构体,返回值会封装成NSNumber或者NSValue对象。这两个类会处理从数字,布尔值到指针和结构体任何类型。然后开以者需要手动转换成原来的类型。尽管valueForKey:会自动将值类型封装成对象,但是setValue:forKey:却不行。你必须手动将值类型转换成NSNumber或者NSValue类型,才能传递过去。
对于自定义对象,KVC也会正确地设值和取值。因为传递进去和取出来的都是id类型,所以需要开发者自己担保类型的正确性,运行时Objective-C在发送消息的会检查类型,如果错误会直接抛出异常。
KVC自带的运算
①简单集合运算符
@sum @avg @count @min @max 相信大家都知道这些运算符的意思
②对象运算符 返回值都是NSArray
@distinctUnionOfObjects //获取去重后的元素
@unionOfObjects//获取所有的元素
Book *book1 = [[Book alloc]init];
book1.name = @"ios";
book1.price = 12;
Book *book2 = [[Book alloc]init];
book2.name = @"ios2";
book2.price = 15;
Book *book3 = [[Book alloc]init];
book3.name = @"ios3";
book3.price = 111;
Book *book4 = [[Book alloc]init];
book4.name = @"ios1";
book4.price = 111;
NSArray *arrBooks = @[book1,book2,book3,book4];
NSNumber *sum = [arrBooks valueForKeyPath:@"@sum.price"];
NSLog(@"sum = %f",sum.floatValue);
NSNumber *avg = [arrBooks valueForKeyPath:@"@avg.price"];
NSLog(@"avg = %f",avg.floatValue);
NSNumber *count = [arrBooks valueForKeyPath:@"@count"];
NSLog(@"count = %f",count.floatValue);
NSNumber *min = [arrBooks valueForKeyPath:@"@min.price"];
NSLog(@"min = %f",min.floatValue);
NSNumber *max = [arrBooks valueForKeyPath:@"@max.price"];
NSLog(@"max = %f",max.floatValue);
NSLog(@"distinctUnionOfObjects");//获取去重后的元素
NSArray *arrDistinch = [arrBooks valueForKeyPath:@"@distinctUnionOfObjects.price"];
NSLog(@"arrDis = %@",arrDistinch);
NSLog(@"UnionOfObjects");//获取所有元素
NSArray *arrUnion = [arrBooks valueForKeyPath:@"@unionOfObjects.price"];
NSLog(@"arrUnion = %@",arrUnion);
总结:KVC常用的两种用法就 对私有变量访问和赋值 和 字典转模型。
对于KVC如果你有好的见解欢迎随时指教!