kvc原理

KVC 全拼 key-value-coding,翻译过来即为 键值编码 。可以直接访问对象的属性,或者给对象的属性赋值。黑魔法之一,很多高级的iOS开发技巧都是基于KVC实现的。 本片文章主要讲解,KVC的实现原理、注意细节、实际应用:KVC原理、KVC赋值和取值,KVC的key、keyPath注意点、KVC的集合处理、数模转换。 这里先创建两个对象,用于下面的举例应用

import <Foundation/Foundation.h>
@interface Author : NSObject{
    NSString *_name;
    //作者出版的书籍,一个作者对应多个书籍对象
    NSArray *_issueBook;
}
@end

//---------------------
#import "Author.h"
@implementation Author
@end

copy success
1
2
3
4
5
6
7
8
9
10
11
12
13
#import <Foundation/Foundation.h>
#import "Author.h"

@interface Book : NSObject{
    Author *_author;
}
//名字
@property(nonatomic,copy) NSString *name;
///价格
@property(nonatomic,assign)float price;
@end

//---------------------
#import "Book.h"
@implementation Book
@end

copy success
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  //----------    KVC键值编码    --------
   Author *author = [[Author alloc] init];
   //设置属性值
   [author setValue:@"莫言" forKey:@"name"];

   //-------   KVC设置作者的书籍数组   -------
   //键值路径:对于一个类中有数组对象的属性进行便捷操作
   Book *book1 = [[Book alloc] init];
   book1.name = @"红高粱";
   book1.price = 9;
   Book *book2 = [[Book alloc] init];
   book2.name = @"蛙";
   book2.price = 6;
   NSArray *array = [NSArray arrayWithObjects:book1,book2, nil];
   [author setValue:array forKeyPath:@"issueBook"];

   //获取属性值
   NSString *name = [author valueForKey:@"name"];
   NSLog(@"%@",name);


    // -----    KVC中键值路径取值   -------
   //基本数据类型会自动被包装成NSNumber,装到数组中
   //得到所有书籍的价格
   NSArray *priceArray = [author valueForKeyPath:@"issueBook.price"];
   NSLog(@"%@",priceArray);
   
   //获取数组的大小
   NSNumber *count = [author valueForKeyPath:@"issueBook.@count"];
   NSLog(@"count=%@",count);
   
   //获取书籍价格的总和
   NSNumber *sum = [author valueForKeyPath:@"[email protected]"];
   NSLog(@"%@",sum);
   //获取书籍的平均值
   NSNumber *avg = [author valueForKeyPath:@"[email protected]"];
   NSLog(@"%@",avg);
   //获取书籍的价格最大值和最小值
   NSNumber *max = [author valueForKeyPath:@"[email protected]"];
   NSNumber *min = [author valueForKeyPath:@"[email protected]"];
   NSLog(@"%@____%@",max,min);

copy success
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42