KVO的高级应用 — valueForKeyPath

作者: isletn | 来源:发表于2017-06-22 14:02 被阅读106次

    实际开发中有发现KVC、KVO的一些有趣的实用技巧,又在网上搜集了一下,发现valueForKeyPath的强大超乎我的想象。

    valueForKeyPath不仅仅只是可以取值那么简单,它可以给容器中每一个对象发送操作消息,并且结果会被保存在一个新的容器中返回。

    下面我们一一列举valueForKeyPath的妙用吧:

    • 集合元素double -> int
    NSArray *array0 = @[@5.7, @7.1];
    NSLog(@"%@", [array0 valueForKeyPath:@"doubleValue.intValue"]);
    

    输出结果:


    image.png
    • 对集合元素执行uppercaseString方法,小写变大写
    NSArray *array1 = @[@"apple",@"banana",@"pineapple",@"orange"];
    NSLog(@"%@",[array1 valueForKeyPath:@"uppercaseString"]);
    

    输出结果:


    image.png
    • 求集合各个元素长度
    NSArray *array1 = @[@"apple",@"banana",@"pineapple",@"orange"];
    NSLog(@"%@", [array1 valueForKeyPath:@"length"]);
    

    输出结果:


    image.png
    • 数组元素数学计算
    NSArray *array2 = @[@0, @10, @40];
    //求和
    NSLog(@"sum = %@", [array2 valueForKeyPath:@"@sum.self"]);
    //平均值
    NSLog(@"avg = %@", [array2 valueForKeyPath:@"@avg.self"]);
    //最大值
    NSLog(@"max = %@", [array2 valueForKeyPath:@"@max.self"]);
    //最小值
    NSLog(@"min = %@", [array2 valueForKeyPath:@"@min.self"]);
    

    输出结果:


    image.png
    • 过滤集合中重复元素
    NSArray *array3 = @[@"mike",@"jine",@"marry",@"mike",@"selly"];
    NSLog(@"%@", [array3 valueForKeyPath:@"@distinctUnionOfObjects.self"]);
    

    输出结果:


    image.png
    • 通过属性名取集合中相应的value集合
    NSDictionary *dataSource = @[@{@"name":@"mike", @"sex":@"man", @"age":@"12"},
                                     @{@"name":@"jine", @"sex":@"women", @"age":@"10"},
                                     @{@"name":@"marry", @"sex":@"women", @"age":@"12"},
                                     @{@"name":@"mike", @"sex":@"man", @"age":@"11"},
                                     @{@"name":@"selly", @"sex":@"women", @"age":@"12"}];
        NSLog(@"name = %@",[dataSource valueForKeyPath:@"name"]);
    

    输出结果:


    image.png
    • 过滤对应属性重复的value,并取出:
    NSLog(@"filterName = %@",[dataSource valueForKeyPath:@"@distinctUnionOfObjects.name"]);
    

    输出结果:


    image.png
    • 通过setValue:forKeyPath:设置UI控件的属性:
    [self.label setValue:[UIColor greenColor] forKeyPath:@"textColor"];
     [self.button setValue:[UIColor orangeColor] forKeyPath:@"backgroundColor"];
     [self.textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
    

    输出结果:


    image.png

    PS相关资料:

    NSKeyValueObserving

    相关文章

      网友评论

        本文标题:KVO的高级应用 — valueForKeyPath

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