gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 11:33:33 26 4
gpt4 key购买 nike

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

最佳答案

因为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];

}

关于ios - 单击按钮时将数据存储在 NSMutable 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51258015/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com