gpt4 book ai didi

ios - NSMutableDictionary 和 NSUserDefaults

转载 作者:行者123 更新时间:2023-11-28 18:34:12 25 4
gpt4 key购买 nike

我正在尝试找出正确的数据结构来保存 'date' => 'value' 的键值

我正在尝试使用 NSMutableDictionary,因为每次用户输入值并按下“保存”时它都必须保存。

但是,尝试将 NSLog 字典的值始终为 null。

- (IBAction)saveWeight:(id)sender
{
NSMutableDictionary *weightLog = [[NSMutableDictionary alloc] init];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

NSString *date = @"12/12/14";

[weightLog setObject:self.weightInput.text forKey:date];

NSLog(@"neweight you entered is %@", self.weightInput.text);
NSLog(@"weightlog is %@", weightLog);

[userDefaults setObject:weightLog forKey:@"Weightlog"];
[userDefaults synchronize];
}

日志输出:

diet[35744:70b] neweight you entered is 13
2014-03-01 16:25:58.712 diet[35744:70b] weightlog is {
"12/12" = 13;
}

最佳答案

当然,只有最后一个值被保存,因为在添加新值之前您不会在 weightLog 中加载以前的值!还有一件事,您应该更改每个值的键。

尝试使用这个(日期将包括年+月+日+时+分+秒,所以每秒点击次数不要超过1次;-D):

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

NSMutableDictionary *weightLog = [NSMutableDictionary dictionaryWithDictionary:[userDefaults objectForKey:@"Weightlog"]];


NSString *date = [NSDateFormatter localizedStringFromDate:[NSDate date]
dateStyle:NSDateFormatterShortStyle
timeStyle:NSDateFormatterFullStyle];

[weightLog setObject:self.weightInput.text forKey:date];

NSLog(@"neweight you entered is %@", self.weightInput.text);
NSLog(@"weightlog is %@", weightLog);

[userDefaults setObject:weightLog forKey:@"Weightlog"];
[userDefaults synchronize];

关于ios - NSMutableDictionary 和 NSUserDefaults,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22121123/

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