直接上代码 输出结果也在相应的代码里标注出来了
//main.m文件
#import <Foundation/Foundation.h>
#import "Student.h" int main(int argc, const char * argv[]) {
@autoreleasepool { NSMutableArray <Student *> *_studentArrM;
NSMutableArray <Student *> *_studentArrMTest; _studentArrM = [NSMutableArray array];
_studentArrMTest = [NSMutableArray array]; Student *s1 = [Student studentWithNum: chinese:90.0 math:96.0 english:100.0];
Student *s2 = [Student studentWithNum: chinese:90.0 math:100.0 english:96.0];
Student *s3 = [Student studentWithNum: chinese:100.0 math:90.0 english:96.0]; [_studentArrM addObject:s1];
[_studentArrM addObject:s2];
[_studentArrM addObject:s3]; double mathAvg = [[_studentArrM valueForKeyPath:@"@avg.math"]doubleValue];
double mathMax = [[_studentArrM valueForKeyPath:@"@max.math"]doubleValue];
double mathMin = [[_studentArrM valueForKeyPath:@"@min.math"]doubleValue];
double mathSum = [[_studentArrM valueForKeyPath:@"@sum.math"]doubleValue];
NSLog(@"数学平均分%f 数学最高分%f 数学最低分%f 所有人的数学总分%f",mathAvg,mathMax,mathMin,mathSum); /*
输出的内容为:数学平均分95.333333 数学最高分100.000000 数学最低分90.000000 所有人的数学总分286.000000 提示:有兴趣的话可以自己多测试几组数据
*/ //接下来试着处理一下数组中的对象的是否有重复的问题
//测试需要我们可以再次给可变数组添加一个重复的对象
[_studentArrM addObject:s2];
[_studentArrM addObject:s2]; NSArray *arrDistinct = [_studentArrM valueForKeyPath:@"@distinctUnionOfObjects.num"];
NSArray *arrUnion = [_studentArrM valueForKeyPath:@"@unionOfObjects.num"]; NSLog(@"DistinctArray %@ \n UnionArray %@",arrDistinct,arrUnion);
/*
输出的内容为:
DistinctArray (
3,
2,
1
)//提示:没有重复的所有值
UnionArray (
1,
2,
3,
2,
2
)//提示:有重复的所有值
*/ //为了处理 多个数组 中的重复值的情况再次添加一个一个对象到测试数组
[_studentArrMTest addObject:s2]; NSLog(@"%@",[@[_studentArrM,_studentArrMTest] valueForKeyPath:@"@distinctUnionOfArrays.num"]);
NSLog(@"%@",[@[_studentArrM,_studentArrMTest] valueForKeyPath:@"@unionOfArrays.num"]);
/*
输出的内容为
(3,
2,
1
)//提示:没有重复的所有值 (1,
2,
3,
2,
2,
2
)//提示:有重复的所有值 */
}
return ;
}
//Student.h文件
#import <Foundation/Foundation.h> @interface Student : NSObject /**
学号
*/
@property (nonatomic,assign)int num;
/**
语文成绩
*/
@property (nonatomic,assign)double chinese;
/**
语文成绩
*/
@property (nonatomic,assign)double math;
/**
语文成绩
*/
@property (nonatomic,assign)double english; - (instancetype)initWithNum:(int)num chinese:(double)chinese math:(double)math english:(double)english; + (instancetype)studentWithNum:(int)num chinese:(double)chinese math:(double)math english:(double)english;
1 //Student.m文件
#import "Student.h" @implementation Student - (instancetype)initWithNum:(int)num chinese:(double)chinese math:(double)math english:(double)english{ self = [super init];
if(self){
_num = num;
_chinese = chinese;
_math = math;
_english = english;
}
return self; } + (instancetype)studentWithNum:(int)num chinese:(double)chinese math:(double)math english:(double)english{ return [[Student alloc]initWithNum:num chinese:chinese math:math english:english]; } @end