我想在每次单击按钮时将数据存储在NSMutableDictionary
的键值对中,并将该字典存储在NSArray
中。
问题-新数据替换了该阵列中的旧数据
代码-
- (void)viewDidLoad {
[super viewDidLoad];
_filledDict = [[NSMutableDictionary alloc] init];
_addedArray = [[NSMutableArray alloc] init];
}
- (IBAction)addMoreClicked:(UIButton *)sender {
NSString *availableTo = [to stringByReplacingOccurrencesOfString:@"" withString:@""];
NSString *from = [[_tfDateFrom.text stringByAppendingString:@" "] stringByAppendingString:_tfTimeFrom.text];
[_filledDict setObject:availableFrom forKey:@"fromDate"];
[_filledDict setObject:availableTo forKey:@"toDate"];
[_addedArray addObject:_filledDict];
_tfDateFrom.text = @"";
_tfDateTo.text = @"";
_tfTimeFrom.text = @"";
_tfTimeTo.text = @"";
}
我得到的结果-
<__NSArrayM 0x60000045d6d0>(
{
fromDate = "2018-08-10 11:16:37";
toDate = "2018-08-10 11:16:39";
},
{
fromDate = "2018-08-10 11:16:37";
toDate = "2018-08-10 11:16:39";
}
)
答案 0 :(得分:1)
由于NSMutableDictionary
和NSMutableArray
是引用类型,因此,当您更新_filledDict
的数据时,它也会在对象中更新,您也添加到了NSMutableArray
您可以简单地将_filledDict
更改为函数的作用域变量以进行修复
- (void)viewDidLoad {
[super viewDidLoad];
// Remove it
// _filledDict = [[NSMutableDictionary alloc] init];
_addedArray = [[NSMutableArray alloc] init];
}
- (IBAction)addMoreClicked:(UIButton *)sender {
// Change to
NSMutableDictionary *filledDict = [[NSMutableDictionary alloc] init];
[filledDict setObject:availableFrom forKey:@"fromDate"];
[filledDict setObject:availableTo forKey:@"toDate"];
[_addedArray addObject:filledDict];
}
答案 1 :(得分:0)
您并非每次都初始化字典,所以它会发生。请找到以下代码。
- (IBAction)addMoreClicked:(UIButton *)sender {
NSString *availableTo = [to stringByReplacingOccurrencesOfString:@"" withString:@""];
NSString *from = [[_tfDateFrom.text stringByAppendingString:@" "] stringByAppendingString:_tfTimeFrom.text];
_filledDict = [[NSMutableDictionary alloc] init];
[_filledDict setObject:availableFrom forKey:@"fromDate"];
[_filledDict setObject:availableTo forKey:@"toDate"];
[_addedArray addObject:_filledDict];
_tfDateFrom.text = @"";
_tfDateTo.text = @"";
_tfTimeFrom.text = @"";
_tfTimeTo.text = @"";
}