您的位置:首页 > 其它

KVC简单用法

2016-01-18 14:47 399 查看
KVC赋值,先创建一个类Model

<span style="font-size:14px;">#import <Foundation/Foundation.h>

@interface Model : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, copy) NSString *gender;

@end</span>

<span style="font-size:14px;">#import "Model.h"

@implementation Model

//用KVC赋值,若没有与key对应属性,需要写此方法。
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{

}

@end</span>


ViewController中:

<span style="font-size:14px;">#import "ViewController.h"
#import "Model.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

//KVC直接赋值
Model *model = [[Model alloc]init];
NSDictionary *dict = @{@"name":@"哈哈",@"gender":@"男",@"age":@18};
[model setValuesForKeysWithDictionary:dict];
[self showInfo:model];

//也可对单一属性赋值
Model *model2 = [[Model alloc]init];
[model2 setValue:dict[@"name"] forKey:@"name"];
[self showInfo:model2];

//若赋值时,Model类中没有与之对应属性,需要在Model.m中写下行方法
//    -(void)setValue:(id)value forUndefinedKey:(NSString *)key{
//
//    }

//    例:Model类中没有aa这个属性,运行崩溃。
Model *model1 = [[Model alloc]init];
NSDictionary *dict1 = @{@"name":@"哈哈",@"gender":@"男",@"aa":@18};
[model1 setValuesForKeysWithDictionary:dict1];
[self showInfo:model1];
}

    //KVC直接赋值
    Model *model = [[Model alloc]init];
    NSDictionary *dict = @{@"name":@"哈哈",@"gender":@"男",@"age":@18};
    [model setValuesForKeysWithDictionary:dict];
    [self showInfo:model];
    
    //也可对单一属性赋值
    Model *model2 = [[Model alloc]init];
    [model2 setValue:dict[@"name"] forKey:@"name"];
    [self showInfo:model2];
    
    //若赋值时,Model类中没有与之对应属性,需要在Model.m中写下行方法
//    -(void)setValue:(id)value forUndefinedKey:(NSString *)key{
//   
//    }
//    例:Model类中没有aa这个属性,运行崩溃。
    Model *model1 = [[Model alloc]init];
    NSDictionary *dict1 = @{@"name":@"哈哈",@"gender":@"男",@"aa":@18};
    [model1 setValuesForKeysWithDictionary:dict1];
    [self showInfo:model1];
    

    printf("\n\nKVC取值:\n");
    NSArray *arrN = @[@1,@2,@3,@4,@5];
    NSDictionary *dicN = @{@"A":arrN};
    NSDictionary *dicN1 = @{@"B":dicN};
    NSDictionary *dic = @{@"C":dicN1,@"B":@"b"};
    
    
    //valueForKeyPath 获取值时,若对象没有keyPath的“键名”,自动进入里面一级查找。
    NSString *dic2 = [dic valueForKeyPath:@"C"];
    NSLog(@"%@",dic2);
    
    //若只获取里面很多级以内的数值时,直接keyPath.keyPath直到要取的那一层为止。
    NSArray *array = [dic valueForKeyPath:@"C.B.A"];
    NSLog(@"%@",array);
    
    //求和、平均值、最大值、最小值
    NSArray *arr = [dic valueForKeyPath:@"C.B.A"];
    NSNumber *count = [arr valueForKeyPath:@"@sum.intValue"];
//    NSNumber *count = [arr valueForKeyPath:@"@avg.intValue"];
//    NSNumber *count = [arr valueForKeyPath:@"@max.intValue"];
//    NSNumber *count = [arr valueForKeyPath:@"@min.intValue"];
    
    //也可直接写成
//    NSNumber *count = [arr valueForKeyPath:@"C.B.A.@max.intValue"];
    NSLog(@"max:%@",count);
 


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  KVC