这让我发疯,我做了一个日志,我看到对象是不同的,但是当我从 回来时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];
}
因此,最终代码被编辑。