【问题标题】:Nested array or nested dictionary?嵌套数组还是嵌套字典?
【发布时间】:2014-02-24 16:07:28
【问题描述】:

我想根据 SUBJECTS 存储 STUDENTS 分数和 cmets。

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

基本上,每个科目分别有mark和cmets。并且每个学生有 3 个科目。并且每个班级有 3 名学生。我如何将它们嵌套在一起?我的大脑被卡住了!

【问题讨论】:

    标签: nsmutablearray nested nsarray nsdictionary nsmutabledictionary


    【解决方案1】:

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

    类.h

    @interface Class : NSObject
    
    @property (nonatomic, strong) NSMutableArray *students;
    
    @end
    

    类.m

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

    学生.h

    @interface Student : NSObject
    
    @property (nonatomic, strong) NSMutableArray *subjects;
    
    @end
    

    学生.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]];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-07
      • 2013-11-09
      • 2018-01-29
      • 1970-01-01
      • 1970-01-01
      • 2012-01-29
      • 2018-05-31
      • 2011-07-07
      相关资源
      最近更新 更多