rick
rick

Reputation: 1115

NSUserDefaults will not write to disk

In my user defaults, I have an array of dictionaries that each represent an object. I am trying to implement a method to change the name of the object, which has the key "name". I am doing this in a KVO compliant subclass of NSObject, as the name is a textfield in an NSTableView.

I am able to find the right dictionary, change the value for the key in that object, and replace that object in the array - NSLog confirms each step of this process. Additionally, the change is reflected in the tableview. However, when it comes to synchronizing the defaults, it just doesn't write. What obvious mistake has been holding me up for almost a day!?

- (void)setName:(NSString *)aName {

if (name && aName != name) {

    NSMutableArray *existingArray = [[NSMutableArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"array"]];

    [existingArray enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) {
        if ([[object valueForKey:@"name"] isEqualToString:name]) {

            NSMutableDictionary *data = [existingArray objectAtIndex:idx];
            [data setObject:aName forKey:@"name"];
            [existingCrates replaceObjectAtIndex:idx withObject:data];
            [[NSUserDefaults standardUserDefaults] setObject:existingCrates forKey:@"crates"];

            NSLog(@"this is the new existingArray: %@", existingArray);
            NSLog(@"this is the new plist: %@", [[NSUserDefaults standardUserDefaults] objectForKey:@"array"]);
            [[NSUserDefaults standardUserDefaults] synchronize];

            name = aName;
            return;
        }
    }];
}

else {
    name = aName;
}

}

Upvotes: 0

Views: 98

Answers (1)

rick
rick

Reputation: 1115

although i was not getting ANY errors indicating it, i was trying to mutate a non-mutable element. fixed by copying the immutable objects into mutable ones and writing them to the user defaults.

Upvotes: 1

Related Questions