-(nullable id)valueForKeyPath:(NSString *)keyPath
1.數(shù)組求和
如果一個(gè)數(shù)組是由NSNumber或者數(shù)字的字符串組成的,可以獲取數(shù)組最大值,最小值,平均值以及求和等等,
//求和
NSArray *array = @[@3, @"100", @47, @4, @8, @86, @"9"];
CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
NSLog(@"%f",sum);//257
//最大值
CGFloat max = [[array valueForKeyPath:@"@max.floatValue"] floatValue];
NSLog(@"%f",max);//100
//最小值
CGFloat min = [[array valueForKeyPath:@"@min.floatValue"] floatValue];
NSLog(@"%f",min);//3
//平均值
CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];
NSLog(@"%f",avg);//36.7
2.操作數(shù)組字符串
如果一個(gè)數(shù)組是由字符串組成的识啦,那么可以直接對數(shù)組內(nèi)所有的字符串統(tǒng)一進(jìn)行操作
lowercaseString:小寫; uppercaseString:大寫
NSArray *array = @[@"AA", @"BB", @"CC",@"DD"];
NSArray *temp = [array valueForKeyPath:@"lowercaseString"];
NSLog(@"%@", temp);
/**
(
aa,
bb,
cc,
dd
)
*/
length:計(jì)算長度
NSArray *array = @[@"AAaa", @"BBb", @"CCc",@"DDDDD"];
NSArray *lengths = [array valueForKeyPath:@"length"];
NSLog(@"%@", lengths);
/**
(
4,
3,
3,
5
)
*/
3.獲取數(shù)組中相同key的元素
1.如果數(shù)組內(nèi)包含的對象是字典赶袄,那么可以直接取出某個(gè)key的所有值:
NSArray *array = @[@{@"name":@"zhangSan",@"age":@"18",@"code":@"99"},
@{@"name":@"liSi",@"age":@"19",@"code":@"80"},
@{@"name":@"wangWu",@"age":@"17",@"code":@"59"}];
NSArray *temp = [array valueForKeyPath:@"name"];
NSLog(@"%@",temp);
/**
(
zhangSan,
liSi,
wangWu
)
*/
2.如果數(shù)組內(nèi)存放的是模型怔揩,同樣可以取出模型數(shù)組其中某個(gè)屬性的值
NSArray *array = @[@"Tom", @"Ben", @"Swetty"];
NSMutableArray *peoples = [NSMutableArray arrayWithCapacity:array.count];
for (int i = 0; i < array.count; i++) {
People *p = [[People alloc]init];
p.name = array[i];
p.age = i;
[peoples addObject:p];
}
NSArray *names = [peoples valueForKeyPath:@"name"];
NSLog(@"%@", names);
/**
(
Tom,
Ben,
Swetty
)
*/
4.數(shù)組去重
1.如果數(shù)組內(nèi)包含重復(fù)的元素妇拯,可以直接去重.
NSArray *array = @[@"qq", @"wechat", @"qq", @"msn", @"wechat"];;
NSArray *temp = [array valueForKeyPath:@"@distinctUnionOfObjects.self"];
NSLog(@"%@",temp);
/**
(
qq,
wechat,
msn
)
*/
5.數(shù)組內(nèi)包含字典粱腻,去重字典某字段的重復(fù)值
如果數(shù)組中包含字典再沧,字典相同字段的值有重復(fù)的尼夺,那么可以直接取出去掉了重復(fù)值的內(nèi)容,先刪除對應(yīng)值的重復(fù)數(shù)據(jù)再取值
NSArray *array = @[
@{@"name": @"zhangsan", @"age": @"1"},
@{@"name": @"zhangsan", @"age": @"2"},
@{@"name": @"lisi",@"age": @"2"},
];
NSArray *temp = [array valueForKeyPath:@"@distinctUnionOfObjects.name"];
NSLog(@"%@",temp);
/**
(
zhangsan,
lisi
)
*/
6.多級字典嵌套取值
如果字典中包含很多層字典,可以很方便取出最內(nèi)層字典的某個(gè)值:
NSDictionary *dic = @{
@"key1": @{
@"key2": @{
@"key3": @"zhangSan"
}
}
};
NSString *key = [dic valueForKeyPath:@"key1.key2.key3"];
NSLog(@"%@",key);
/**
zhangSan
*/
6.改變 UITextfield 的 placeholder 的顏色
比起重寫 - (void)drawPlaceholderInRect:(CGRect)rect; 要方便太多!
[addressTextField setValue:[UIColor redColor] forKeyPath:@”_placeholderLabel.textColor”];