OGeek|极客世界-中国程序员成长平台

标题: ios - 填充 NSmutableDictionary 错误 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 14:56
标题: ios - 填充 NSmutableDictionary 错误

问候。我有一个 NSmutableDictionary 并想填充它。

- (IBAction)addCourseUIButton *)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]);

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

更新:感谢哈维尔的建议。它解决了这个问题。但是现在在新的情况下,只有一个键可以容纳一个内容。以下内容将覆盖旧内容,请问这是为什么呢?



Best Answer-推荐答案


NSMutableDictionary *contents 不会被 Controller 的任何对象保留,当方法完成时,该对象将自动释放。

尝试将内容声明为属性:

@property (nonatomic,strong) NSMutableDictionary *contents;

关于ios - 填充 NSmutableDictionary 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29523092/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4