Core Data not saving transformable NSMutableDictionary

后端 未结 1 827
余生分开走
余生分开走 2020-12-18 08:21

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

@         


        
1条回答
  •  有刺的猬
    2020-12-18 09:17

    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];
    

    0 讨论(0)
提交回复
热议问题