iOS开发iOS DeveloperiOS面试题+基础知识

KVO的高级应用 — valueForKeyPath

2017-06-22  本文已影响106人  isletn

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

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

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

NSArray *array0 = @[@5.7, @7.1];
NSLog(@"%@", [array0 valueForKeyPath:@"doubleValue.intValue"]);

输出结果:


image.png
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
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
NSLog(@"filterName = %@",[dataSource valueForKeyPath:@"@distinctUnionOfObjects.name"]);

输出结果:


image.png
[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

上一篇 下一篇

猜你喜欢

热点阅读