// 创建student对象
Student *stu1 = [[Student alloc] init];
// 用点语法赋值
stu1.name = @"杨过";
stu1.age = 24;
stu1.height = 188.8;
// 用点语法取值
NSLog(@"%@, %ld, %.2f", stu1.name, stu1.age, stu1.height);
// 用方法赋值
[stu1 setName:@"小龙女"];
[stu1 setAge:33];
[stu1 setHeight:177.4];
// 用方法取值
NSLog(@"%@, %ld, %.2f", [stu1 name], [stu1 age], [stu1 height]);
// 使用KVC赋值
//1.优先找setName
//2._name
//3._isName
//4.name
//5.isName
//如果没有,空,产生异常
//可以重写解决异常:
// 主要由两种异常,解决方法.
// 第一:当key为非对象类型,且Value设置为nil的时候,会调用这个方法,系统是默认实现是抛出一个异常,我们可以重写这个方法,解决Value为nil的问题
// - (void)setNilValueForKey:(NSString *)key;
// - (void)setNilValueForKey:(NSString *)key
// {
// }
// 第二,当key不存在的时候,会调用这个方法,系统的默认实现是抛出一个异常,我们可以重写这个方法,解决key不存在的问题
// - (void)setValue:(id)value forUndefinedKey:(NSString *)key;
//- (void)setValue:(id)value forUndefinedKey:(NSString *)key
// {
// }
// #pragma mark 处理当你写错key的情况
// - (void)setValue:(id)value forUndefinedKey:(NSString *)key
// {
// NSLog(@"value = %@, key = %@", value, key);
// }
[stu1 setValue:@"大雕" forKey:@"name"];
[stu1 setValue:@29 forKey:@"age"];
[stu1 setValue:@188 forKey:@"height"];
// teacher类是复合在student类中,teacher类有一个name属性
// 创建teacher对象
stu1.teacher = [Teacher new];
// 使用路径给teacher的name赋值
// setValue: forKeyPath 可以给变量的变量的变量赋值
//当没有teacher的空间时,也没法给teacher的name赋值,
//当把teacher开辟了空间,通过keyPath就可以赋值了
[stu1 setValue:@"小泽" forKeyPath:@"teacher.name"];
NSLog(@"teacher = %@",stu1.teacher.name);
// 使用KVC取值
NSLog(@"%@, %@, %@", [stu1 valueForKey:@"name"], [stu1 valueForKey:@"age"], [stu1 valueForKey:@"height"]);
/*******************************KVC的常见用法:与字典配合使用**************************************/
/***************************以上都不写,一个字典+setValuesForKeysWithDictionary方法搞定***********/
// 创 建 学生对象
Student *student = [Student new];
// 将学生信息放进字典
NSDictionary *dictionary = @{
@"name": @"金庸",
@"age":@88,
@"height":@177,
@"teacher":[Teacher new],
};
// 利用字典给student赋值
[student setValuesForKeysWithDictionary:dictionary];
NSLog(@"%@,%ld,%.2f,%@",student.name, student.age, student.height, student.teacher.name);
KVC的一些基础知识和用法
最新推荐文章于 2019-05-25 22:50:47 发布