你好,游客 登录 注册 搜索
背景:
阅读新闻

Objective-C语法之KVC的使用

[日期:2012-07-26] 来源:blog.csdn.net/totogo2010  作者:totogo2010 [字体:大 中 小]

4、操作集合

在Student类中加入数组NSArray,用来表示其他的学生。这样我们可以添加多个其他的学生,再用集合操作计算学生的分数,最高分,最低分,平均分等

  1. #import <Foundation/Foundation.h>   
  2. @class Course;  
  3. @interface Student : NSObject  
  4. {  
  5.     NSString *name;  
  6.     Course *course;  
  7.     NSInteger point;  
  8.     NSArray *otherStudent;  
  9. }  
  10. @end 

.m文件实现不变。

在main函数中添加三个学生,添加到数组中,然后求平均分,最高,最低分,学生数量

  1. #import "Student.h"   
  2. #import "Course.h"   
  3. int main(int argc, const char * argv[])  
  4. {  
  5.     @autoreleasepool {  
  6.         Student *student = [[[Student alloc]init ]autorelease];  
  7.         [student setValue:@"张三" forKey:@"name"];  
  8.         NSString *name = [student valueForKey:@"name"];  
  9.         NSLog(@"学生姓名:%@",name);  
  10.           
  11.         [student setValue:@"88" forKey:@"point"];  
  12.         NSString *point = [student valueForKey:@"point"];  
  13.         NSLog(@"分数:%@", point);  
  14.           
  15.         Student *student1 = [[[Student alloc]init]autorelease];  
  16.         Student *student2 = [[[Student alloc]init]autorelease];  
  17.         Student *student3 = [[[Student alloc]init]autorelease];  
  18.         [student1 setValue:@"65" forKey:@"point"];  
  19.         [student2 setValue:@"77" forKey:@"point"];  
  20.         [student3 setValue:@"99" forKey:@"point"];  
  21.         NSArray *array = [NSArray arrayWithObjects:student1,student2,student3,nil];  
  22.         [student setValue:array forKey:@"otherStudent"];  
  23.         NSLog(@"其他学生的成绩%@", [student valueForKeyPath:@"otherStudent.point"]);  
  24.         NSLog(@"共%@个学生", [student valueForKeyPath:@"otherStudent.@count"]);  
  25.         NSLog(@"最高成绩:%@", [student valueForKeyPath:@"otherStudent.@max.point"]);  
  26.         NSLog(@"最低成绩:%@", [student valueForKeyPath:@"otherStudent.@min.point"]);  
  27.         NSLog(@"平均成绩:%@", [student valueForKeyPath:@"otherStudent.@avg.point"]);  
  28.     }  
  29.     return 0;  
  30. }  

运行打印结果

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

linux
相关资讯       Objective-C 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款