填充NSmutableDictionary错误

时间:2015-04-08 18:57:03

标签: ios arrays xcode nsmutablearray nsmutabledictionary

问候语。我有一个NSmutableDictionary,想要填充它。

- (IBAction)addCourse:(UIButton *)sender {
    //NSMutableArray *keys = [[NSMutableArray alloc] init];
    NSMutableDictionary *contents = [[NSMutableDictionary alloc] init];

    //To add content and keys

    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 *AddKey=[NSString stringWithFormat:@"%@ %@",num,season];

    [contents setObject:[NSMutableArray arrayWithObjects:course, nil] forKey:AddKey];
   // NSLog(@"%@", key);//test key here, it works
    NSLog(@"Dictionary: %@", [contents description]);//test dictionary here

...}

在这里,我有一个按钮,当我按下它时,numseason并形成一个键,相关的course将被添加到词典中。但是,当我用

进行测试时
NSLog(@"Dictionary: %@", [contents description]);

显示字典中的所有内容,仅显示我选择中的最后一条记录。换句话说,在填充字典时,先前的数据被后一个数据覆盖。有什么问题吗?

更新:感谢Javier的建议。它解决了这个问题。但现在在新的情况下,只有一个密钥可以容纳一个内容。以下内容将覆盖旧内容,为什么会这样?

1 个答案:

答案 0 :(得分:2)

NSMutableDictionary *内容不会被控制器的任何对象保留,当方法完成时,该对象将自动释放。

尝试将内容声明为属性:

@property (nonatomic,strong) NSMutableDictionary *contents;