单击按钮

时间:2018-07-10 05:50:16

标签: ios objective-c nsmutablearray nsmutabledictionary

我想在每次单击按钮时将数据存储在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";
}
)

2 个答案:

答案 0 :(得分:1)

由于NSMutableDictionaryNSMutableArray是引用类型,因此,当您更新_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 = @"";

}