KVC的几种常用方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了KVC的几种常用方法相关的知识,希望对你有一定的参考价值。

KVC的使用1:

以Person为例:

@interface Person : NSObject

@property (nonatomic, copy) NSString *name;

@end

 

属性的方法:

Person *person = [[Person alloc] init];

person.name = @"大锤";

NSLog(@"%@", person.name);

 

KVC方法:

Person *person = [[Person allocinit];

[person setValue:@"盖聂" forKey:@"name"];

NSLog(@"%@", [person valueForKey:@"name"]);

 

 

KVC的使用2:

还是以Person为例:

@interface Person : NSObject

@property (nonatomic, copy) NSString *name;

@property (nonatomic, copy) NSString *gender;

@end

 

属性方法:

Person *person = [[Person allocinit];

person.name = @"大锤";

person.gender = @"男";

NSLog(@"%@", person.name);

 

KVC方法:

Person *person = [[Person allocinit];

NSDictionary *dict = @{@"name" : @"哈哈哈", @"gender" : @"man"};

[person setValuesForKeysWithDictionary:dict];

NSLog(@"%@, %@", [person valueForKey:@"name"], [person valueForKey:@"gender"]);

 

 

KVC的使用3:

以Person和Teacher为例:

@class Teacher;

@interface Person : NSObject

@property (nonatomic, copy) NSString *name;

@property (nonatomic, copy) NSString *gender;

@property (nonatomic, retain) Teacher *tea;

@end

 

@interface Teacher : NSObject

@property (nonatomic, copy) NSString *name;

@property (nonatomic, copy) NSString *sex;

@property (nonatomic, assign) NSInteger age;

@end

 

属性的方法:

Person *p = [[Person alloc] init];

Teacher *t = [[Teacher alloc] init];

p.tea = t;

t.name = @"哈哈哈";

NSLog(@"%@", p.tea.name);

 

KVC的方法:

Person *person = [[Person alloc] init];

Teacher *t = [[Teacher allocinit];

 

[person setValue:t forKey:@"teacher"];

[person setValue:@"卫庄" forKeyPath:@"tea.name"];

NSLog(@"%@", [person valueForKeyPath:@"tea.name"]);

其实如果我们Person类重写init的话:

- (instancetype)init {

    if (self = [super init]) {

        _tea = [[Teacher alloc] init];

    }

    return self;

}

就可以直接像下面这么写了:

Person *person = [[Person alloc] init];

[person setValue:@"卫庄" forKeyPath:@"tea.name"];

NSLog(@"%@", [person valueForKeyPath:@"tea.name"]);

 

 

以上是关于KVC的几种常用方法的主要内容,如果未能解决你的问题,请参考以下文章

数组的几种常用方法

得到Class类的几种方式与常用方法

反向传值的几种常用方法

sql 的几种常用方法

Python常用的几种去重方法

css中常用的几种居中方法