@通常,我们都是通过属性的set和get方法来赋值和取值,这里介绍用Key-Value-Coding(KVC)键值编码来给类的属性赋值和取值.
1.基本方式(setValue:forKey: valueForKey)
// ---定义一个Student类(.m文件无任何操作) #import <Foundation/Foundation.h> @class HMTClass; @interface HMTStudent : NSObject{ NSString * _name; BOOL _test; BOOL _isTest; BOOL test; BOOL isTest; } @property (nonatomic,copy)NSString * name; @property (nonatomic,copy)NSString * sex; @property (nonatomic,assign)NSInteger age; @property (nonatomic,strong) HMTClass * hmtClass; @end // ---main文件 HMTStudent * student = [[HMTStudent alloc] init]; student.hmtClass = [[HMTClass alloc] init]; student.name = @"humingtao”; // set方法赋值 // KVC赋值 [student setValue:@“mawei is dog" forKey:@"name”]; [student setValue:@"m" forKey:@"sex"]; [student setValue:@(10) forKey:@"age"]; // 取值 NSLog(@"%s__%d__|%@",__FUNCTION__,__LINE__,[student valueForKey:@"name"]); @特别注意: 我在类里面还定义了4个BOOL值变量,用来验证KVC访问属性键顺序 [student setValue:@(YES) forKey:@"test”]; 结果是:_test—>_isTest—>test—>isTest
// 创建一个班级类 @interface HMTClass : NSObject @property (nonatomic,copy)NSString * name; @end 然后前面第一点中在Student类中写了一个班级属性hmtClass HMTClass *hmtClass = [[HMTClass alloc]init]; [hmtClass setValue:@"宇宙一班" forKey:@"name"]; [student setValue:hmtClass forKey:@"hmtClass"]; NSString *hmtClassName = [student valueForKeyPath:@"hmtClass.name"]; //也可以这样存值 [student setValue:@"宇宙一班" forKeyPath:@"hmtClass.name"]; student.hmtClass.name = [student valueForKeyPath:@"hmtClass.name"];
#import <Foundation/Foundation.h> @class HMTClass; @interface HMTStudent : NSObject { NSString *_name; NSInteger number; } @end [student setValue:@"100" forKeyPath:@"number"]; NSString *number = [student valueForKey:@"number"]; 可见用NSString*类型设置的属性值@"100",而我们的属性是NSInteger类型的,存取都没有问题。
在Student类中加入数组NSArray,用来表示其他的学生。
#import <Foundation/Foundation.h> @class HMTClass; @interface HMTStudent : NSObject { NSArray *manyStudents; } @end Student *student1 = [[HMTStudent alloc]init]; Student *student2 = [[HMTStudent alloc]init]; Student *student3 = [[HMTStudent alloc]init]; [student1 setValue:@"200" forKey:@"number"]; [student2 setValue:@"300" forKey:@"number"]; [student3 setValue:@"400" forKey:@"number"]; NSArray *array = [NSArray arrayWithObjects:student1,student2,student3,nil]; [student setValue:array forKey:@"manyStudents"]; NSLog(@"%@",[student valueForKeyPath:@"manyStudents.number"]); 打印出来是数组(200,300,400)