//先用init方式初始化person对象
TRPerson *firstPerson = [[TRPerson alloc] initWithName:@"Maggie" withAge:18];
//点语法获取
NSLog(@"使用点语法获取名字:%@;年龄:%d", firstPerson.name, firstPerson.age);
//KVC方式一获取(针对都是OC对象类型)
/* 注意点:
1.key和属性名字一模一样;
2.重写方法,获取一个不存在的属性的值
3.给C语言的基本类型设置为nil,会抛异常;需要重写方法,给定初始值
*/
NSString *nameFromKVC = [firstPerson valueForKey:@"name"];
NSLog(@"使用KVC方式一获取名字:%@;年龄:%@", nameFromKVC, [firstPerson valueForKey:@"age"]);
//如果使用KVC方式取一个不存在的属性值(给定不存在的key)
NSLog(@"使用KVC方式获取不存在的属性值:%@", [firstPerson valueForKey:@"salary"]);
//使用KVC的方式设置name/age
TRPerson *secondPerson = [TRPerson new];
[secondPerson setValue:@"Bob" forKey:@"name"];
[secondPerson setValue:nil forKey:@"age"];
NSLog(@"使用KVC方式一设置name:%@; 设置age:%@",[secondPerson valueForKey:@"name"], [secondPerson valueForKey:@"age"]);
////////KVC设置和获取属性值的方式二(keyPath)////
TRPerson *thirdPerson = [[TRPerson alloc] initWithName:@"Jonny" withAge:20];
TRAddress *address = [TRAddress new];
thirdPerson.address = address;
//使用KVC方式设置
[thirdPerson setValue:@"北京市-朝阳区-中国" forKeyPath:@"address.simpleAddress"];
[thirdPerson setValue:@"潘家园-xxx大厦-6层" forKeyPath:@"address.detailAddress"];
//使用KVC方式取值
NSLog(@"简单地址:%@; 详细地址:%@",[thirdPerson valueForKeyPath:@"address.simpleAddress"], [thirdPerson valueForKeyPath:@"address.detailAddress"]);
网友评论