单击按钮时将数据存储在 NSMutable 数组中

Store data in NSMutable Array on button click

我想在 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";
}
)

你不是每次都初始化词典所以它发生了。请找到以下代码。

  - (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 = @"";

}

因为NSMutableDictionaryNSMutableArray是引用类型,所以当你更新_filledDict的数据时,它会在你添加到[=12=的对象中更新] 也是。

您可以简单地更改 _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]; 

}