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

时间:2015-04-07 22:19:29

标签: ios arrays nsmutablearray nsmutabledictionary

我有三个可变阵列

@interface PickeriviewAndTableViewController ()
//Create mutableArray for tableView

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

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

然后我想使用按钮

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

}

我的问题是:如何通过替换这些“不知道如何”代码来完成我的代码?

更新:为了更清楚,密钥是从msgYear[ ]msgSeason[ ]生成的,例如'2001年秋季',字典充满了例如'化学', '数学'。

1 个答案:

答案 0 :(得分:1)

指向其他问题的链接有助于为您要实现的目标提供背景信息。

您不需要在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是无序的,因此您需要考虑如何在表格中订购数据。您可以使用数组来保存原始代码中的键,然后对此数组进行排序。