0

我想存储学生标记&基于对象的评论。嵌套数组或嵌套字典?

NSArray *students = @[@"Johns",@"James",@"Michelle",nil]; 
NSArray *subjects = @[@"Maths",@"Science",@"History",nil]; 

NSArray *marks = @[@"80",@"60",@"86",nil]; 
NSArray *comments = @[@"Very Good",@"Moderate",@"Excellent",nil]; 

基本上,每个主题分别有标记和评论。每个学生有3个科目。每个班级有3名学生。我如何将它们嵌套在一起?我的大脑被卡住了!

回答

0

您可以编写一个Student和Class类。主题可以由NSDictionary用两个键值对来描述(一个用于标记,另一个用于注释)。学生可以有一个NSArray类型的实例var(这将是一个Subject词典数组)。类可以有类型的NSArray的实例变量(这将是学生对象的数组)

Class.h

@interface Class : NSObject 

@property (nonatomic, strong) NSMutableArray *students; 

@end 

Class.m

-(id)initWithStudents:(NSMutableArray *)newStudents{ 
    if(self = [super init]) { 
     self. students = newStudents 
    } 
    return self; 
} 

Student.h

@interface Student : NSObject 

@property (nonatomic, strong) NSMutableArray *subjects; 

@end 

Student.m

-(id)initWithStudents:(NSMutableArray *)newSubjects{ 
    if(self = [super init]) { 
     self.subjects = newSubjects 
    } 
    return self; 
} 

创建你的主题,学生和班级的对象如下:

NSMutableDictionary *subject1 = [NSMutableDictionary dictionaryWithObjects:@[@"80", @"Very Good"] forKeys:@[@"Marks", @"Comments"]]; 
NSMutableDictionary *subject2 = [NSMutableDictionary dictionaryWithObjects:@[@"70", @"Good"] forKeys:@[@"Marks", @"Comments"]]; 
NSMutableDictionary *subject3 = [NSMutableDictionary dictionaryWithObjects:@[@"40", @"Poor"] forKeys:@[@"Marks", @"Comments"]]; 
Student *student1 = [[Student alloc] initWithSubjects:@[subject1, subject2, subject3]]; 

//Create student2 and student 3 in similar fashion. 

Class *class1 = [[Class alloc] initWithStudents:@[srudent1, student2, student3]];