从两个可变数组中获取 NSmutableDictionary 键

Getting NSmutableDictionary key from two mutable arrays

我有三个可变数组

@interface PickeriviewAndTableViewController ()
//Create mutableArray for tableView

@property(strong,nonatomic)NSMutableArray *msgYear;
@property(strong,nonatomic)NSMutableArray *msgSeason;
@property(strong,nonatomic)NSMutableArray *msgCourse;

我想使用从前两个数组 msgYear[ ]msgSeason[ ] 生成的键将元素添加到数组 msgCourse[ ]

然后我想使用按钮填充 msgCourse[] 数组

- (IBAction)addCourse:(UIButton *)sender {


    //To get value from pickerView, prepare for key and contents

    NSInteger numRow=[picker selectedRowInComponent:kNumComponent];//0=1st,1=2nd,etc
    NSInteger SeaRow=[picker selectedRowInComponent:kSeaComponent];//0=fall,1=spring,2=summer
    NSInteger CourseRow=[picker selectedRowInComponent:kCourseComponent];

    NSString *num=Number[numRow];
    NSString *season=Season[SeaRow];
    NSString *course=Course[CourseRow];

    NSString *CourseToAdd=[[NSString alloc ]initWithFormat:@"%@ ",course];
    NSString *SeasonToAdd=[[NSString alloc ]initWithFormat:@"%@ ",season];
    NSString *YearToAdd=[[NSString alloc ]initWithFormat:@"%@ ",num];

// Try to generate key from YearToAdd and SeasonToAdd and fill in content
   NSMutableArray *keys = [[NSMutableArray alloc] init];
   NSMutableDictionary *contents = [[NSMutableDictionary alloc] init];

   NSString *keyFromYearAndSeason = @"Don't_know_what_to_do_here";
  [contents setObject:[NSArray arrayWithObjects:@"Don't_know_how", nil] forKey:keyFromYearAndSeason];

[keys addObject:keyFromYearAndSeason];

[self setSectionKeys:keys];
[self setSectionContents:contents];

}

我的问题是:如何通过替换这些 "Don't know how" 行代码来完成我的代码?

更新:为了更清楚,密钥是从 msgYear[ ]msgSeason[ ] 生成的,例如“2001 年秋季”,字典中充满了课程,例如'chemistry','math'.

您的其他问题的 link 有助于为您试图实现的目标提供背景信息。

您不需要在 addButtton 方法中创建字典或数组 - 您应该将字典作为已经初始化的 属性。 然后,在添加按钮中检索与键关联的数组 - 如果值为 nil,则创建一个新数组并将课程放入。如果值不是 nil,只需将课程添加到数组中即可。

@property (strong,nonatomic) NSMutableDictionary *tableEntries;  // alloc/init this in viewDidLoad


- (IBAction)addCourse:(UIButton *)sender {

    //To get value from pickerView, prepare for key and contents

    NSInteger numRow=[picker selectedRowInComponent:kNumComponent];//0=1st,1=2nd,etc
    NSInteger SeaRow=[picker selectedRowInComponent:kSeaComponent];//0=fall,1=spring,2=summer
    NSInteger CourseRow=[picker selectedRowInComponent:kCourseComponent];

    NSString *num=Number[numRow];
    NSString *season=Season[SeaRow];
    NSString *course=Course[CourseRow];

    NSString *key=[NSString stringWithFormat:@"%@ %@",num,season];

    NSMutableArray *courses=self.tableEntries[key];
    if (courses == nil) {
        courses=[NSMutableArray new];
        self.tableEntries[key]=courses;
    }

    [courses addObject:course];

}

NSDictionary 是无序的,因此您需要考虑如何对 table 中的数据进行排序。您可以使用一个数组来保存原始代码中的键,然后对该数组进行排序。