gpt4 book ai didi

ios - NSUserDefaults无法更新nsmutablearray

转载 作者:行者123 更新时间:2023-12-01 18:14:06 26 4
gpt4 key购买 nike

我在NSUserDefaults中保存了一个nsmutableArray。

在以下情况下,似乎数组中的所有元素都等于0,即使在这种情况下位置1和位置5的值应为1而不是0。我知道NSUserDefaults元素是不可变的,但是...我确实在检索值时添加了mutableCopy。

我哪里错了?

//create array

NSMutableArray *objArray = [[NSMutableArray alloc] init];
for (int i=0; i< 100;i++) [objArray addObject:@"0"];
[objArray replaceObjectAtIndex:1 withObject:@"1"];
[[NSUserDefaults standardUserDefaults] setObject:objArray forKey:name];

// update

elementPosition = 5;
NSMutableArray *objArray = [[NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:name]] mutableCopy];
[objArray replaceObjectAtIndex:elementPosition withObject:@"1"];


//check the array


NSMutableArray *objArray = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:nameFile]];
BOOL displayContent = true;


for (int i=0; i<[objArray count];i++)
{

if ([[objArray objectAtIndex:i] isEqualToString:@"0"])
{
displayContent = false;
}
}

最佳答案

用以下代码替换代码:

//create array

NSMutableArray *objArray = [[NSMutableArray alloc] init];
for (int i=0; i< 100;i++){
[objArray addObject:@"0"];
}
[objArray replaceObjectAtIndex:1 withObject:@"1"];
[[NSUserDefaults standardUserDefaults] setObject:objArray forKey:name];

//First mistake. Missing this. Without this line the data is not saved in NSUserDefaults
[[NSUserDefaults standardUserDefaults] synchronize];

// update

elementPosition = 5;
NSMutableArray *objArray = [[NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:name]] mutableCopy];
[objArray replaceObjectAtIndex:elementPosition withObject:@"1"];

//Second Mistake. You did not update the NSUserDefaults again.
[[NSUserDefaults standardUserDefaults] setObject:objArray forKey:name];
[[NSUserDefaults standardUserDefaults] synchronize];




//check the array
NSMutableArray *objArray = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:name]];
BOOL displayContent = true;


for (int i=0; i<[objArray count];i++)
{

if ([[objArray objectAtIndex:i] isEqualToString:@"0"])
{
displayContent = false;
}

//Third mistake. Once the BOOL is made false in an if block you have to make it true in the else block, otherwise the value of the BOOL will remain false even if it does not enter the if block.
else{
displayContent = true;
}
NsLog(@"ArrayIndex=[%d];DisplayContent=[%d]",i,displayContent);
}

快乐的编码。

关于ios - NSUserDefaults无法更新nsmutablearray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24486365/

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