4、操作集合
在Student类中加入数组NSArray,用来表示其他的学生。这样我们可以添加多个其他的学生,再用集合操作计算学生的分数,最高分,最低分,平均分等
- #import <Foundation/Foundation.h>
- @class Course;
- @interface Student : NSObject
- {
- NSString *name;
- Course *course;
- NSInteger point;
- NSArray *otherStudent;
- }
- @end
.m文件实现不变。
在main函数中添加三个学生,添加到数组中,然后求平均分,最高,最低分,学生数量
- #import "Student.h"
- #import "Course.h"
- int main(int argc, const char * argv[])
- {
- @autoreleasepool {
- Student *student = [[[Student alloc]init ]autorelease];
- [student setValue:@"张三" forKey:@"name"];
- NSString *name = [student valueForKey:@"name"];
- NSLog(@"学生姓名:%@",name);
- [student setValue:@"88" forKey:@"point"];
- NSString *point = [student valueForKey:@"point"];
- NSLog(@"分数:%@", point);
- Student *student1 = [[[Student alloc]init]autorelease];
- Student *student2 = [[[Student alloc]init]autorelease];
- Student *student3 = [[[Student alloc]init]autorelease];
- [student1 setValue:@"65" forKey:@"point"];
- [student2 setValue:@"77" forKey:@"point"];
- [student3 setValue:@"99" forKey:@"point"];
- NSArray *array = [NSArray arrayWithObjects:student1,student2,student3,nil];
- [student setValue:array forKey:@"otherStudent"];
- NSLog(@"其他学生的成绩%@", [student valueForKeyPath:@"otherStudent.point"]);
- NSLog(@"共%@个学生", [student valueForKeyPath:@"otherStudent.@count"]);
- NSLog(@"最高成绩:%@", [student valueForKeyPath:@"otherStudent.@max.point"]);
- NSLog(@"最低成绩:%@", [student valueForKeyPath:@"otherStudent.@min.point"]);
- NSLog(@"平均成绩:%@", [student valueForKeyPath:@"otherStudent.@avg.point"]);
- }
- return 0;
- }
运行打印结果
2012-07-20 16:09:17.101 objectiveC[2857:403] 学生姓名:张三
2012-07-20 16:09:17.104 objectiveC[2857:403] 分数:88
2012-07-20 16:09:17.105 objectiveC[2857:403] 其他学生的成绩(
65,
77,
99
)
2012-07-20 16:09:17.106 objectiveC[2857:403] 共3个学生
2012-07-20 16:09:17.106 objectiveC[2857:403] 最高成绩:99
2012-07-20 16:09:17.107 objectiveC[2857:403] 最低成绩:65
2012-07-20 16:09:17.108 objectiveC[2857:403] 平均成绩:80.333333333333333333333333333333333333
还可以求总和 @sum。
相关阅读:Objective-C语法之KVO的使用 http://www.linuxidc.com/Linux/2012-07/66457.htm
