嵌套数组还是嵌套字典?

时间:2014-02-24 16:07:28

标签: nsmutablearray nested nsarray nsdictionary nsmutabledictionary

我想存储STUDENTS标记&评论基于主题。

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名学生。我如何将它们嵌套在一起?我的大脑卡住了!

1 个答案:

答案 0 :(得分:0)

您可以编写学生和班级课程。 NSDictionary可以用两个Key-Pair值描述Subject(一个用于Marks,一个用于注释)。学生可以拥有NSArray类型的实例var(这将是一个主题词典数组)。类可以有一个NSArray类型的实例变量(这将是一个Student对象数组)

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;
}

按如下方式创建Subjects,Student和Class对象:

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]];