iOS KVC 简介
//作用-:利用kvc 赋值 (key value coding)键值编码
void test(){
Person *person = [[Person alloc]init];
[person setValue:@"王五" forKey:@"name"];
[person setValue:@"19" forKey:@"money"];
NSLog(@"---%@ ---- %.2f",person.name,person.money);
}
//作用二:修改类的私有成员变量(UIpageControl)
void test2(){
Person *person = [[Person alloc]init];
[person printAge];
[person setValue:@"88" forKeyPath:@"_age"];
[person printAge];
}
//作用三:字典转模型
void test3(){
NSDictionary *dict = @{@"name":@"小黄",@"money":@190.88};
Person *person = [Person personWithDict:dict];
NSLog(@"%@",person);
}
//作用四:利用kvc取值
void test4(){
Person *person = [[Person alloc]init];
person.name = @"你好";
NSString *name = [person valueForKey:@"name"];
NSLog(@"%@",name);
}
//作用五:(模型转字典)
void test5(){
Person *person = [[Person alloc]init];
person.name = @"你好";
person.money = 32.32;
NSDictionary * dict = [person dictionaryWithValuesForKeys:@[@"name",@"money"]];
NSLog(@"%@",dict);
}
//作用六: 取出所有模型中的某个属性
void test6(){
// 取出所有模型中的某个属性
Person *person1 = [[Person alloc]init];
person1.name = @"你好";
person1.money = 92.32;
Person *person2 = [[Person alloc]init];
person2.name = @"lisi";
person2.money = 82.32;
Person *person3 = [[Person alloc]init];
person3.name = @"wangwu";
person3.money = 892.32;
NSArray *allPersons = @[person1,person2,person3];
NSArray *allPesonName = [allPersons valueForKeyPath:@"name"];
NSLog(@"%@",allPesonName);
}
//模型
#import <Foundation/Foundation.h>
#import "Dog.h"
NS_ASSUME_NONNULL_BEGIN
@interface Person : NSObject
//{
// int _age;//ios9之前默认私有变量
//}
@property (nonatomic, weak) NSString *name;
@property (nonatomic, weak) NSString *_id;
@property (nonatomic, weak) NSString *descriptionCus;
@property (nonatomic, strong) Dog *dog;
@property (nonatomic, assign) float money;
-(void)printAge;
-(instancetype)initWithDict:(NSDictionary *)dict;
+(instancetype)personWithDict:(NSDictionary *)dict;
@end
#import "Person.h"
@implementation Person
{
int _age;//ios9之后放这里,默认私有变量
}
- (instancetype)init
{
self = [super init];
if (self) {
_age = 8;
}
return self;
}
-(void)printAge{
NSLog(@"==age== %d===",_age);
}
-(NSString *)description{
return [NSString stringWithFormat:@"===%@===%.2f",self.name,self.money];
}
-(instancetype)initWithDict:(NSDictionary *)dict{
if (self = [super init]) {
[self setValuesForKeysWithDictionary:dict];
// self.name = dict[@"name"];
// self.money = [dict[@"money"] floatValue];
}
return self;
}
+(instancetype)personWithDict:(NSDictionary *)dict{
return [[self alloc]initWithDict:dict];
}
//防止后台返回开发中的关键字
-(void)setValue:(id)value forKey:(NSString *)key{
if ([key isEqualToString:@"id"]) {
self._id = value;
}else if ([key isEqualToString:@"description"]){
self.descriptionCus = value;
}
}
//找不到key,此方法防止崩溃,赋值空
-(void)setNilValueForKey:(NSString *)key{
[self setValue:@"" forKey:key];
}
本文地址:https://blog.csdn.net/yanPingWang_8/article/details/107372857
下一篇: 045.集群存储-CSI存储机制