Core Data not saving transformable NSMutableDictionary
Asked Answered
E

1

5

I have two classes: Profile and Config. A Profile contains an NSSet of Config objects. Both Profile and Config are NSManagedObject subclasses.

@interface Profile : NSManagedObject

@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSSet *configs;

- (void)print;

@end

Here is the Config class

@interface Config : NSManagedObject

@property (nonatomic, retain) NSString * otherdata;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSMutableDictionary *myDict;
@property (nonatomic, retain) Profile *profile;

- (void)print;

@end

The dictionary myDict has NSString *keys and values. Now when I make any changes to myDict, I call the NSManagedObject save method and that works fine with no errors. As long as I do not kill the app, everything behaves as expected.

But when I force kill the app (either in Xcode or by double pressing the home button and killing it in the row of buttons at the bottom) and then restart the app, the data in myDict reverts to what was there before, ie the new data was not actually saved. It only appeared to be saved before I killed the app.

myDict is listed as Transformable inside the xcdatamodeld file. I tried it without specifying any NSTransformer class. I also tried it specifying a transformer class MyDictTransformer, and in Config I added this code:

In Config.h:

@interface MyDictTransformer : NSValueTransformer

@end

In Config.m:

@implementation MyDictTransformer

+ (Class)transformedValueClass
{
    return [NSMutableDictionary class];
}

+ (BOOL)allowsReverseTransformation
{
    return YES;
}

- (id)transformedValue:(id)value
{
    return [NSKeyedArchiver archivedDataWithRootObject:value];
}

- (id)reverseTransformedValue:(id)value
{
    return [NSKeyedUnarchiver unarchiveObjectWithData:value];
}

@end

Also at top of Config.m I have this:

//
// from: https://mcmap.net/q/1920601/-core-data-not-updating-a-transformable-attribute
//

+ (void)initialize {
    if (self == [Config class]) {
        MyDictTransformer *transformer = [[MyDictTransformer alloc] init];
        [NSValueTransformer setValueTransformer:transformer forName:@"MyDictTransformer"];
    }
}

Also in AppDelegate, in both applicationDidEnterBackground and applicationWillTerminate I call saveContext:

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil)
    {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
        {
            /*
             Replace this implementation with code to handle the error appropriately.

             abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
             */
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        } 
    }
}

No matter what I have tried, it simply does not save the dictionary in Config. It saves any other changes in things like config.name but not in config.myDict.

A) What am I doing wrong? B) How can I fix this, even if I have to use some other data structure than an NSMutableDictionary to save the data?

Exsect answered 5/3, 2014 at 23:27 Comment(3)
So you explicitly call saveContext after changes have been made? Do you just have one managedObjectContext?Jumpoff
First, NSDictionary is NSCoder compliant, so you do not need a custom transformer. You can use the standard one. It sounds like you are not really saving the data. What kind of stack are you using? Single MOC on main queue, nested child/parent, UIManagedDocument, something else?Spittoon
Yes I have just one managedObjectContext. It is a single object I create in the AppDelegate. I even checked in real time to see if the managedObjectContext has a parent. It did not.Exsect
C
26

You've declared myDict as an NSMutableDictionary which is a big red flag.

Managed object attributes should never be a mutable type

Chances are, you're using myDict something like this:

someConfig.myDict[@"someKey"] = @"someValue";
[context save:&error];

The problem is, you're not calling a setter method of someConfig so you've done nothing to inform it that an attribute has been changed. And even though you're calling save:, the context doesn't bother saving unchanged objects.

Strictly speaking, you could probably get away with calling [someConfig didChangeValueForKey:@"myDict"] every time you change myDict. I wouldn't recommend it though because it's easy to forget and error prone.

It would better to declare myDict as non-mutable and use it like this:

@property (nonatomic, retain) NSDictionary *myDict;
...
NSMutableDictionary *updatedDict = [someConfig.myDict mutableCopy];
updatedDict[@"someKey"] = @"someValue";
someConfig.myDict = [updatedDict copy];
[context save:&error];
Crossbred answered 6/3, 2014 at 4:12 Comment(4)
Awesome awesome awesome! The NSDictionary approach works great. You Sir are an IOS programming God.Exsect
helped me, was exactly my problem +1Nimbostratus
Thanks a lot. Could not get away with didChangeValueForKey so I had to use a non-mutable dictionary in the model and create a mutableCopy for modifications.Roundish
Shouldn't it be enough to call willChangeValueForKey:, make the change, then call didChangeValueForKey:? It doesn't work for me unfortunately. I guess I'll have to use the NSDictionary approach and make a mutable copy when I set the value. Seems crazy to have to do that though. Extra memory needed for this unfortunately.Ferminafermion

© 2022 - 2024 — McMap. All rights reserved.