美文网首页
03--KVC/KVO本质01--KVC 初探

03--KVC/KVO本质01--KVC 初探

作者: 修_远 | 来源:发表于2020-07-02 22:32 被阅读0次

    [TOC]

    本章介绍 KVC 的常见用法

    准备条件

    • SRPerson 类
    typedef struct {
        float x, y, z;
    } ThreeFloats;
    
    @interface SRPerson : NSObject
    {
        @public
        NSString* myName;
    }
    
    @property (nonatomic, copy) NSString *name;
    @property (nonatomic, strong) NSArray *array;
    @property (nonatomic, strong) NSMutableArray *mArray;
    @property (nonatomic, assign) int age;
    @property (nonatomic) ThreeFloats threeFloats;
    @property (nonatomic, strong) SRStudent *student;
    
    @end
    
    • SRStudent 类
    @interface SRStudent : NSObject
    
    @property (nonatomic, copy)   NSString          *name;
    @property (nonatomic, copy)   NSString          *subject;
    @property (nonatomic, copy)   NSString          *nick;
    @property (nonatomic, assign) int               age;
    @property (nonatomic, assign) int               length;
    @property (nonatomic, strong) NSMutableArray    *penArr;
    
    @end
    

    一般 setter 方法

    • 测试代码
    person.name = @"SR_Name";
    person.age  = 18;
    person->myName = @"My_Name";
    NSLog(@"%@", person);
    
    • 输出
    [myName] : My_Name
    [name] : SR_Name
    [array] : (null)
    [mArray] : (null)
    [age] : 18
    [threeFloats] : 0.000000, 0.000000, 0.000000
    [student] : (null)
    

    1. Key-Value Coding (KVC) : 基本类型

    • 测试代码
    [person setValue:@"KVC_Name" forKey:@"name"];
    [person setValue:@19 forKey:@"age"];
    [person setValue:@"KVC_My_Name" forKey:@"myName"];
    NSLog(@"%@", person);
    
    • 输出
    [myName] : KVC_My_Name
    [name] : KVC_Name
    [array] : (null)
    [mArray] : (null)
    [age] : 19
    [threeFloats] : 0.000000, 0.000000, 0.000000
    [student] : (null)
    

    2. KVC 集合类型

    • 测试代码
    person.array = @[@"1", @"2", @"3"];
    NSLog(@"%@", person);
    // 更改 array 的值 : 通过修改 array
    NSArray* tempArr1 = [person valueForKey:@"array"];
    tempArr1 = @[@"110", @"2", @"3"];
    [person setValue:tempArr1 forKey:@"array"];
    NSLog(@"%@", person);
    // 更改 array 的值 : 通过 KVC 的方式
    NSMutableArray* tempArr2 = [person mutableArrayValueForKey:@"array"];
    tempArr2[0] = @"120";
    NSLog(@"%@", person);
    
    • 输出
    [myName] : KVC_My_Name
    [name] : KVC_Name
    [array] : (
        1,
        2,
        3
    )
    [mArray] : (null)
    [age] : 19
    [threeFloats] : 0.000000, 0.000000, 0.000000
    [student] : (null)
    
    [myName] : KVC_My_Name
    [name] : KVC_Name
    [array] : (
        110,
        2,
        3
    )
    [mArray] : (null)
    [age] : 19
    [threeFloats] : 0.000000, 0.000000, 0.000000
    [student] : (null)
    
    [myName] : KVC_My_Name
    [name] : KVC_Name
    [array] : (
        120,
        2,
        3
    )
    [mArray] : (null)
    [age] : 19
    [threeFloats] : 0.000000, 0.000000, 0.000000
    [student] : (null)
    

    3. 集合操作符

    3.1 集合操作符 : 字典操作

    • 测试代码
    - (void)dictionaryTest {
        NSDictionary* dict = @{
            @"name" : @"dict_name",
            @"nick" : @"dn",
            @"subject" : @"iOS",
            @"age" : @18,
            @"length" : @188
        };
        
        SRStudent* student = [[SRStudent alloc] init];
        // 字典转模型
        [student setValuesForKeysWithDictionary:dict];
        NSLog(@"%@", student);
        // 键数组转模型到字典
        NSArray* keyArr = @[@"name", @"age"];
        NSDictionary* dic = [student dictionaryWithValuesForKeys:keyArr];
        NSLog(@"dic : %@", dic);
    }
    
    • 输出
    2020-06-23 13:44:15.364904+0800 001--KVC初探[9196:195892] SRStudent
    [name] : dict_name
    [subject] : iOS
    [nick] : dn
    [age] : 18
    [length] : 188
    [penArr] : (null)
    2020-06-23 13:44:15.365225+0800 001--KVC初探[9196:195892] dic : {
        age = 18;
        name = "dict_name";
    }
    

    3.2 集合操作符 : KVC消息传递

    • 测试代码
    - (void)arrayMessagePass {
        NSArray* array = @[@"ZhangSan", @"LiSi", @"WangWu"];
        // 获取 value 的长度 : length
        NSArray* lenStr = [array valueForKeyPath:@"length"];
        NSLog(@"lenStr : %@", lenStr);
        // 将 value 转成小写字母 : lowercaseString
        NSArray* lowStr = [array valueForKeyPath:@"lowercaseString"];
        NSLog(@"lowStr : %@", lowStr);
    }
    
    • 输出
    2020-06-23 13:44:15.365425+0800 001--KVC初探[9196:195892] lenStr : (
        8,
        4,
        6
    )
    2020-06-23 13:44:15.365533+0800 001--KVC初探[9196:195892] lowStr : (
        zhangsan,
        lisi,
        wangwu
    )
    

    3.3 集合操作符 : 集合操作符

    • 测试代码
    // @avg     : 平均数
    // @count   : 计数
    // @max     : 最大值
    // @min     : 最小值
    // @sum     : 求和
    - (void)aggregationOperator {
        NSMutableArray* sArr = [NSMutableArray array];
        for (int i=0; i<6; i++) {
            SRStudent* s = [SRStudent new];
            NSDictionary* dict = @{
                @"name" : @"xiaoming",
                @"age" : @(18+i),
                @"nick" : @"dabai",
                @"length" : @(180 + 2*arc4random_uniform(5)),
            };
            [s setValuesForKeysWithDictionary:dict];
            [sArr addObject:s];
        }
        NSLog(@"length >>>> %@", [sArr valueForKey:@"length"]);
        
        float avg = [[sArr valueForKeyPath:@"@avg.length"] floatValue];
        NSLog(@"avg : %f", avg);
        
        int count = [[sArr valueForKeyPath:@"@count.length"] intValue];
        NSLog(@"count : %d", count);
        
        int max = [[sArr valueForKeyPath:@"@max.length"] intValue];
        NSLog(@"max : %d", max);
        
        int min = [[sArr valueForKeyPath:@"@min.length"] intValue];
        NSLog(@"min : %d", min);
        
        int sum = [[sArr valueForKeyPath:@"@sum.length"] intValue];
        NSLog(@"sumsum : %d", sum);
    }
    
    • 输出
    2020-06-23 13:44:15.365670+0800 001--KVC初探[9196:195892] length >>>> (
        184,
        180,
        188,
        186,
        186,
        184
    )
    2020-06-23 13:44:15.366726+0800 001--KVC初探[9196:195892] avg : 184.666672
    2020-06-23 13:44:15.366918+0800 001--KVC初探[9196:195892] count : 6
    2020-06-23 13:44:15.367035+0800 001--KVC初探[9196:195892] max : 188
    2020-06-23 13:44:15.367305+0800 001--KVC初探[9196:195892] min : 180
    2020-06-23 13:44:15.367608+0800 001--KVC初探[9196:195892] sumsum : 1108
    

    3.4 数组操作符 @distinctUnionOfObjects @unionOfObjects

    • 测试代码
    - (void)arrayOperator {
        NSMutableArray* sArr = [NSMutableArray array];
        for (int i=0; i<6; i++) {
            SRStudent* s = [SRStudent new];
            NSDictionary* dict = @{
                @"name" : @"xiaoming",
                @"age" : @(18+i),
                @"nick" : @"dabai",
                @"length" : @(180 + 2*arc4random_uniform(5)),
            };
            [s setValuesForKeysWithDictionary:dict];
            [sArr addObject:s];
        }
        NSLog(@"length >>>> %@", [sArr valueForKey:@"length"]);
        // 返回操作对象指定属性的集合
        NSArray* arr1 = [sArr valueForKeyPath:@"@unionOfObjects.length"];
        NSLog(@"unionOfObjects arr : %@", arr1);
        // 返回操作对象指定属性的集合 -- 去重
        NSArray* arr2 = [sArr valueForKeyPath:@"@distinctUnionOfObjects.length"];
        NSLog(@"distinctUnioOfObjects arr : %@", arr2);
    }
    
    • 输出
    2020-06-23 13:44:15.368240+0800 001--KVC初探[9196:195892] length >>>> (
        180,
        182,
        180,
        182,
        184,
        188
    )
    2020-06-23 13:44:15.368883+0800 001--KVC初探[9196:195892] unionOfObjects arr : (
        180,
        182,
        180,
        182,
        184,
        188
    )
    2020-06-23 13:44:15.369436+0800 001--KVC初探[9196:195892] distinctUnioOfObjects arr : (
        182,
        188,
        184,
        180
    )
    

    3.5 嵌套集合(array&set)操作 @distinctUnionOfArrays @unionOfArrays @distinctUnionOfSets

    • 测试代码
    - (void)arrayNesting {
        NSMutableArray* sArr1 = [NSMutableArray array];
        for (int i=0; i<6; i++) {
            SRStudent* s = [SRStudent new];
            NSDictionary* dict = @{
                @"name" : @"xiaoming",
                @"age" : @(18+i),
                @"nick" : @"dabai",
                @"length" : @(180 + 2*arc4random_uniform(5)),
            };
            [s setValuesForKeysWithDictionary:dict];
            [sArr1 addObject:s];
        }
        NSMutableArray* sArr2 = [NSMutableArray array];
        for (int i=0; i<6; i++) {
            SRStudent* s = [SRStudent new];
            NSDictionary* dict = @{
                @"name" : @"xiaohei",
                @"age" : @(18+i),
                @"nick" : @"didi",
                @"length" : @(180 + 2*arc4random_uniform(5)),
            };
            [s setValuesForKeysWithDictionary:dict];
            [sArr2 addObject:s];
        }
        // 嵌套数组
        NSArray* nestArr = @[sArr1, sArr2];
        NSLog(@"nestArr : %@", nestArr);
        // 返回操作对象指定属性的集合
        NSArray* arr1 = [nestArr valueForKeyPath:@"@unionOfArrays.length"];
        NSLog(@"arr1 : %@", arr1);
        // 返回操作对象指定属性的集合 -- 去重
        NSArray* arr2 = [nestArr valueForKeyPath:@"@distinctUnionOfArrays.length"];
        NSLog(@"arr : %@", arr2);
    }
    
    • 输出
    2020-06-23 13:47:02.717828+0800 001--KVC初探[9271:198128] arr1 : (
        184,
        184,
        188,
        180,
        182,
        186,
        182,
        180,
        188,
        180,
        188,
        180
    )
    2020-06-23 13:47:02.718036+0800 001--KVC初探[9271:198128] arr : (
        184,
        182,
        180,
        188,
        186
    )
    
    • 测试代码
    - (void)setNesting {
        NSMutableSet* sSet1 = [NSMutableSet set];
        for (int i=0; i<6; i++) {
            SRStudent* s = [SRStudent new];
            NSDictionary* dict = @{
                @"name" : @"xiaoming",
                @"age" : @(18+i),
                @"nick" : @"dabai",
                @"length" : @(180 + 2*arc4random_uniform(5)),
            };
            [s setValuesForKeysWithDictionary:dict];
            [sSet1 addObject:s];
        }
        NSMutableSet* sSet2 = [NSMutableSet set];
        for (int i=0; i<6; i++) {
            SRStudent* s = [SRStudent new];
            NSDictionary* dict = @{
                @"name" : @"xiaohei",
                @"age" : @(18+i),
                @"nick" : @"didi",
                @"length" : @(180 + 2*arc4random_uniform(5)),
            };
            [s setValuesForKeysWithDictionary:dict];
            [sSet2 addObject:s];
        }
        NSLog(@"set1.length : %@", [sSet1 valueForKey:@"length"]);
        NSLog(@"set2.length : %@", [sSet2 valueForKey:@"length"]);
        // 嵌套数组
        NSSet* nestSet = [NSSet setWithObjects:sSet1, sSet2, nil];
        // 返回操作对象指定属性的集合 -- 并集
        NSArray* arr2 = [nestSet valueForKeyPath:@"@distinctUnionOfSets.length"];
        NSLog(@"arr : %@", arr2);
    }
    
    • 输出
    2020-06-23 13:47:02.718341+0800 001--KVC初探[9271:198128] set1.length : {(
        182,
        188,
        184,
        186
    )}
    2020-06-23 13:47:02.718501+0800 001--KVC初探[9271:198128] set2.length : {(
        182,
        188,
        184,
        180
    )}
    2020-06-23 13:47:02.718725+0800 001--KVC初探[9271:198128] arr : {(
        182,
        188,
        184,
        180,
        186
    )}
    

    3.6 array取值

    • 测试代码
    - (void)arrayGetValueDemo {
        SRStudent* student = [SRStudent new];
        student.penArr = [NSMutableArray arrayWithObjects:@"pen0", @"pen1", @"pen2", @"pen3", nil];
        // 这里有问题
    //    NSArray* arr = [student valueForKey:@"pens"];
    //    NSLog(@"pens : %@", arr);
        
        NSEnumerator* enumerator = [student.penArr objectEnumerator];
        NSString* str = nil;
        while (str = [enumerator nextObject]) {
            NSLog(@"str : %@", str);
        }
    }
    
    • 输出
    2020-06-23 13:47:02.728408+0800 001--KVC初探[9271:198128] str : pen0
    2020-06-23 13:47:02.728576+0800 001--KVC初探[9271:198128] str : pen1
    2020-06-23 13:47:02.728682+0800 001--KVC初探[9271:198128] str : pen2
    2020-06-23 13:47:02.728816+0800 001--KVC初探[9271:198128] str : pen3
    

    4. KVC : 访问非对象属性

    • 测试代码
    // 设置 值
    ThreeFloats floats = {1., 2., 3.};
    NSValue* value = [NSValue valueWithBytes:&floats objCType:@encode(ThreeFloats)];
    [person setValue:value forKey:@"threeFloats"];
    NSLog(@"%@", person);
    // 取值
    NSValue* result = [person valueForKey:@"threeFloats"];
    NSLog(@"value : %@", result);
    ThreeFloats retTh;
    [result getValue:&retTh];
    NSLog(@"th x:%f, y:%f, z:%f", retTh.x, retTh.y, retTh.z);
    
    • 输出
    [myName] : KVC_My_Name
    [name] : KVC_Name
    [array] : (
        120,
        2,
        3
    )
    [mArray] : (null)
    [age] : 19
    [threeFloats] : 1.000000, 2.000000, 3.000000
    [student] : (null)
     value : {length = 12, bytes = 0x0000803f0000004000004040}
     th x:1.000000, y:2.000000, z:3.000000
    

    相关文章

      网友评论

          本文标题:03--KVC/KVO本质01--KVC 初探

          本文链接:https://www.haomeiwen.com/subject/robdqktx.html