KVC键值编码

Peson *p = [Person alloc] init];

Person *p1 = [p1 alloc] init];

p1.name = @"Tom";

p1.age = 18;

Person *p2 = [Person alloc] init];

p2.name = @"Jack";

p2.age = 28;

//set 方法使用 KVC

[p setValue:@"Jim" forKeyPath:@"name"];

[p setValue:@"10" forKeyPath:@"age"] 

//get方法

NNString *name = [p valueForKeyPath:@"name"];

int age = [[p valueForKeyPath:@"age"] intValue ];

//模型转字典

//后面穿的数组是我要转化为字典的所有的 key 值

NSDictionary *dict= [p dictionaryWithValuesForKeys:@[@"name",@"age"]];

NSLog(@"dict = %@",dict);

//多个数据模型的操作

NSArray *persons = @[p,p1,p2];

//取出 persons 数组里面所有的 person 对象那么属性的值

NSArray *names = [person valueForKeyPath:@"name"];

NSLog(@"name = %@",names);

//数据模型里的模型属性

Book *book = [Book alloc] init];

book.name = @"iOS 宝典";

p.book = book;

NSString *bookNM = p.book.name;

NSString *bookName = [p valueForKeyPath:@"book.name"];

NSString *bN = [p.book valueForKeyPath:@"name"];

NSLog(@"%@",bN);

你可能感兴趣的:(KVC键值编码)