我正在尝试更新保存在 UserDefaults 中的字典。
但是,它只是不想更新给定索引处的对象。我不知道为什么。具有它的值的对象保持不变。
代码:
- (void) saveUser
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *users = [[NSMutableArray alloc] initWithArray:[defaults objectForKey:@"users"]];
BOOL userAlreadyAdded = FALSE;
NSUInteger count = 0;
for (NSMutableDictionary *user in users) {
if ([[user objectForKey:@"username"] isEqualToString:[defaults objectForKey:@"username"]]) {
NSLog(@"User found: %@", user);
[user setObject:sid forKey:@"sess"];
[user setObject:mid forKey:@"seca"];
[users replaceObjectAtIndex:count withObject:user];
userAlreadyAdded = TRUE;
}
count++;
}
if (!userAlreadyAdded) {
NSMutableDictionary *userToAdd = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
[defaults objectForKey:@"username"], @"username",
sid, @"sess",
mid, @"seca",
nil];
[users addObject:userToAdd];
}
NSLog(@"USERS TO SAVE: %@", users);
[defaults setObject:users forKey:@"users"];
[defaults synchronize];
}