作用:提供了另一种 为对象的属性赋值及读取对象属性的编写代码的方式
—————Dog.h———————
@interface Dog : NSObject
@property(nonatomic,strong)NSString *name;
@end
----Book.h----
@interface Book : NSObject
@property(nonatomic,strong)NSString *name;
@property(nonatomic)float price;
@end
----Student.h---
#import <Foundation/Foundation.h>
#import "Dog.h"
#import "Book.h"
@interface Student : NSObject
{
float _score;
}
@property(nonatomic,strong)NSString *name;
@property(nonatomic,strong)Dog *dog;
@property(nonatomic,strong)NSArray *books;
@end
---Student.m----
@implementation Student
- (instancetype)init
{
self = [super init];
if (self) {
self.dog = [[Dog alloc]init];
Book *b1 = [[Book alloc]init];
b1.name = @"数学";
b1.price = 35.5;
Book *b2 = [[Book alloc]init];
b2.name = @"语文";
b2.price = 31.8;
self.books = @[b1,b2];
}
return self;
}
@end
----ViewController.m----
#import "ViewController.h"
#import "Student.h"
Student *stu = [[Student alloc]init];
//1.为私有成员赋值
[stu setValue:@98 forKey:@"score"];
[stu setValue:@"张3" forKey:@"name"];
NSLog(@"%@ %@",[stu valueForKey:@"name"],[stu valueForKey:@"score"]);
//2.访问id类型的对象
id stu2 = [[Student alloc]init];
[stu2 setValue:@"李4" forKey:@"name"];
[stu2 setValue:@95.5 forKey:@"score"];
NSLog(@"%@ %f",[stu2 valueForKey:@"name"],[[stu2 valueForKey:@"score"] floatValue]);
//3.为层级类型的属性赋值
[stu setValue:@"ww" forKeyPath:@"dog.name"];
NSLog(@"%@",stu.dog.name);
//4.使用自带的运算符对数组属性进行运算
//获取所有图书的价格
NSLog(@"%@",[stu valueForKeyPath:@"books.price"]);
//获取所有图书的总价sum/平均价格avg/最大价格max/最小价格min
NSLog(@"%@",[stu valueForKeyPath:@"[email protected]"]);
//获取图书的总数
NSLog(@"%@",[stu valueForKeyPath:@"[email protected]"]);