标签:
KVC 概念:Key Value Coding 作用: 1.KVC可以给对象的私有变量赋值(UIPageControl) 2.用于字典转模型(MJExtension) 3.通过KVC取出私有变量的值 4.模型对象转字典(了解) 使用注意: 1.设置key/keyPath位置的字符串必须保证有对应的属性(或者_属性) 2.字典转模型的使用注意: 1> 必须保证字典中对应key在模型中能找到对应的属性 2> 模型中的属性可以在字典中没有对应的Key setValue:forKey:和setValue:forKeyPath区别 keyPath可以根据内部点语法,进一步查找对应的key
int main(int argc, const char * argv[]) { @autoreleasepool { /* // 1.创建Person对象 Person *p = [[Person alloc] init]; p.book = [[Book alloc] init]; [p setValue:@"18" forKey:@"age"]; [p setValue:@"20" forKeyPath:@"age"]; // [p.book setValue:@"100" forKey:@"price"]; // [p.book setValue:@"200" forKeyPath:@"price"]; // [p setValue:@"300" forKey:@"book.price"]; [p setValue:@"300" forKeyPath:@"book.price"]; */ // MJExtension NSDictionary *dict = @{ @"name" : @"why", @"height" : @"1.89", @"age" : @"18", @"weight" : @"60", @"book" : @{@"price" : @"200"} }; Person *p = [Person personWithDict:dict]; NSLog(@"%@", p.book); } return 0; } void notice() { // 1.注意一 /* // 1.创建Person对象 Person *p = [[Person alloc] init]; // 2.给p对象的属性赋值 // [p setValue:@"20" forKeyPath:@"aga"]; */ // 2.注意二 NSDictionary *dict = @{ @"name" : @"why", @"height" : @"1.89", @"age" : @"18", @"weight" : @"60" }; Person *p = [Person personWithDict:dict]; NSLog(@"age:%ld", p.age); } void getValue() { // 1.创建Person对象 Person *p = [[Person alloc] init]; // 2.给属性赋值 p.name = @"xiaobai"; p.age = 1; // NSLog(@"name:%@ age:%ld height:%@", p.name, p.age, [p valueForKeyPath:@"height"]); /* NSMutableDictionary *dict = [NSMutableDictionary dictionary]; [dict setObject:p.name forKey:@"name"]; */ NSDictionary *dict = [p dictionaryWithValuesForKeys:@[@"name", @"age", @"height"]]; NSLog(@"%@", dict); // NSArray<NSString *> *array = nil; // NSDictionary<NSString *, id> 泛型 } void setValue() { /* // 1.创建Person对象 Person *p = [[Person alloc] init]; // 2.给p属性赋值 // p.name = @"why"; [p setValue:@"lmj" forKey:@"name"]; // [p setValue:@"1.88" forKey:@"_height"]; [p setValue:@"1.88" forKeyPath:@"height"]; NSDictionary *dict = @{ @"name" : @"why", @"height" : @"1.89", @"age" : @"18" }; p.name = dict[@"name"]; [p setValue:dict[@"height"] forKeyPath:@"height"]; p.age = [dict[@"age"] integerValue]; */ // 1.定义字典 NSDictionary *dict = @{ @"name" : @"why", @"height" : @"1.89", @"age" : @"18" }; // 2.字典转模型 Person *p = [Person personWithDict:dict]; NSLog(@"%@", p); }
标签:
原文地址:http://www.cnblogs.com/mshong1616/p/KVC.html