当前位置: 代码迷 >> 综合 >> iOS keyValue方法的使用
  详细解决方案

iOS keyValue方法的使用

热度:37   发布时间:2024-03-08 11:45:48.0
//TZPerson是普通的继承自NSObject的类
TZPerson.h
#import <Foundation/Foundation.h>@interface TZPerson : NSObject@property (nonatomic, strong) NSString* name;@property (nonatomic, assign) int age;@property (nonatomic, strong) NSString* nick;@property (nonatomic, assign) float height;@endTZPerson.m
@implementation TZPerson
// 赋值key值不存在
- (void) setValue:(id)value forUndefinedKey:(NSString *)key {NSLog(@"key = %@值不存在 ", key);
}@end//在外部view中使用keyValue 来调用TZPerson的属性
ViewController.m
/// KVC字典操作
- (void) dictionaryTest {TZPerson* p = [TZPerson new];NSDictionary* dict = @{@"name":@"Tom",@"age":@18,@"nick":@"Cat",@"height":@180,@"dd":@"helo"};//根据字典里的key给P对象赋对应的value值[p setValuesForKeysWithDictionary:dict];NSLog(@"p.name = %@, p.age = %d, p.nick =%@, p.height = %f", p.name, p.age, p.nick, p.height);NSArray* keys = @[@"name", @"age"];NSDictionary* dict1 = [p dictionaryWithValuesForKeys:keys];NSLog(@"%@", dict1);}/// KVC消息传递  array
- (void) arrayKVCTest {/*对数组而言,valueForKey方法的作用是把valueForKey的参数以消息的方式发送给数组的每一个元素*/NSArray* arr = @[@"Monday", @"Tuesday", @"Wednesday"];//获取arr数组中每一个元素的length属性并返回一个数组NSArray* lengthArr = [arr valueForKey:@"length"];NSLog(@"%@", lengthArr);//arr数组中每一个元素执行lowercaseString方法并结果返回给lowercaseArr数组NSArray* lowercaseArr = [arr valueForKey:@"lowercaseString"];NSLog(@"%@", lowercaseArr);
}/// 聚合操作符  @avg、@count、@max、@min、@sum
- (void) contrainerTest {NSMutableArray* students = [NSMutableArray array];for (int i = 0; i < 6; i++) {TZPerson* student = [TZPerson new];NSDictionary* dict = @{@"name":@"Tom",@"age":@(18+i),@"nick":@"Cat",@"height":@(1.65 + 0.02*arc4random_uniform(6)),};[student setValuesForKeysWithDictionary:dict];[students addObject:student];}NSLog(@"%@", [students valueForKey:@"height"]);/// 平均身高, @avg是获取平均值的聚合运算符,其他的以此类推float avg = [[students valueForKeyPath:@"@avg.height"] floatValue];NSLog(@"%f", avg);}
/// 数组操作符 @distinctUnionOfObjects @unionOfObjects
- (void) contrainerArrayTest {NSMutableArray* students = [NSMutableArray array];for (int i = 0; i < 6; i++) {TZPerson* student = [TZPerson new];NSDictionary* dict = @{@"name":@"Tom",@"age":@(18+i),@"nick":@"Cat",@"height":@(1.65 + 0.02*arc4random_uniform(6)),};[student setValuesForKeysWithDictionary:dict];[students addObject:student];}NSLog(@"%@", [students valueForKey:@"height"]);//distinctUnionOfObjects数组中去重NSArray* arr = [students valueForKeyPath:@"@distinctUnionOfObjects.height"];NSLog(@"arr = %@", arr);//unionOfObjects不去重NSArray* arr1 = [students valueForKeyPath:@"@unionOfObjects.height"];NSLog(@"arr1 = %@", arr1);
}