这让我发疯,我做了一个日志,我看到对象不同,但当我从NSUserDefaults
回来时,所有对象都是一样的。
我的代码:
- (void)breakTrapsToSave:(NSDictionary*)trapsDict firstTimeUpdate:(Boolean)firstTimeUpdate
{
// If traps already save
// we will get them from NSUserDefaults
// and then update them
if (!firstTimeUpdate)
{
allTraps = [self.sharedPrefs objectForKey:@"arrayOfAllTraps"];
}
// JSON Parsing
tempA = trapsDict[@"Envelope"];
tempB = tempA[@"Body"];
tempC = tempB[@"getTrapsResponse"];
tempD = tempC[@"getTrapsResult"];
tempE = tempD[@"TRAPS"];
self.lastUpdate = tempE[@"lastUpdate"];
[[NSUserDefaults standardUserDefaults] setObject:self.lastUpdate forKey:@"last_update"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"Traps latest updated at: %@", self.lastUpdate);
tempF = tempE[@"TRAP"];
if (tempF.count <= 0)
{
newTrapsUpdates = false;
NSLog(@"NO NEW TRAPS!");
}
else
{
newTrapsUpdates = true;
NSLog(@"NEW TRAPS FOUND");
[tempF enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
tempA = tempF[idx];
NSString *finalResult;
NSString *key;
NSMutableDictionary *singleTrap = [[NSMutableDictionary alloc] init];
for (int i=0; i < node.count; i++)
{
finalResult = tempA[node[i]];
key = node[i];
if ([finalResult length] <= 0)
{
finalResult = @"0";
}
singleTrap[key] = finalResult;
}
if (allTraps.count <= 0)
{
allTraps = [[NSMutableArray alloc] initWithObjects:singleTrap, nil];
}
else
{
[allTraps addObject:singleTrap];
}
counter = idx;
}];
allTraps = [[IDANNetroads sharedInstance] removeDuplicatedFromArray:allTraps];
// Save all traps
[[NSUserDefaults standardUserDefaults] setObject:allTraps forKey:@"arrayOfAllTraps"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"Total Traps: %d", allTraps.count);
NSLog(@"Total New Traps: %d", counter);
}
}
我做了一个日志,我看到allTraps[idx] = singleTrap;
应该是不同的,但是当我打印NSLog(@"allTraps: %@", allTraps);
的日志时,我看到所有对象都是最后一个对象。
修改
最终,我替换了singleTrap分配,现在它在枚举块中:
NSMutableDictionary *singleTrap = [[NSMutableDictionary alloc] init];
我添加了这段代码:
if (allTraps.count <= 0)
{
allTraps = [[NSMutableArray alloc] initWithObjects:singleTrap, nil];
}
else
{
[allTraps addObject:singleTrap];
}
因此,最终代码已经过编辑。
答案 0 :(得分:2)
无论singleTrap
是什么,您都会反复改变它并在allTraps
数组中存储对同一对象的另一个引用。您需要为allTraps
列表中的每个条目创建(实例化)新项目。
看起来singleTrap
是一个字符串数组,所以请尝试:
allTraps[idx] = [singleTrap copy];