Skip navigation.
 
mlRe: Strategy for read only Templates with Core Data
FROM : George Orthwein
DATE : Mon Jun 05 20:35:18 2006

I decided to intercept the changes by overriding setValue:ForKeyPath: 
in my NSManagedObject subclass and it seems to be working well. If 
the object is a "template" then I make a copy of it and make changes 
on the copy instead.

I thought I had read before that overriding setValue:ForKeyPath: is 
generally a bad idea. However, after searching for 45 minutes I'm not 
seeing where I read that, I'm only seeing a warning about efficiency 
in the docs. Anyway, I'm not re-implementing it... I'm just calling 
the super version.

Still, could calling the super version cause problems?

Here's my code:

- (void)setValue:(id)value forKeyPath:(NSString *)keyPath
{
   // if default is yes then this is a template we want to copy rather 
than modify
   if ([[self valueForKey:@"default"] boolValue]==YES) {
       // create new managed object - (probably should insert into moc 
directly, rather than this keypath silliness)
       BackgroundImage *newBg = [[[NSApp delegate] 
valueForKeyPath:@"inspectorController.backgroundController"] newObject];

       // copy the default's attributes
       NSMutableDictionary *attributes = [[self 
dictionaryWithValuesForKeys:[[self entity] attributeKeys]] mutableCopy];

       // mark it as NOT a default template
       [attributes setValue:[NSNumber numberWithBool:NO] 
forKeyPath:@"default"];

       // set name to be +" copy"
       [attributes setValue:[NSString stringWithFormat:@"%@ copy",[self 
valueForKey:@"name"]] forKeyPath:@"name"];

       // copy attributes to newBg
       [newBg setValuesForKeysWithDictionary:attributes];

       // select newBg
       [[[NSDocumentController sharedDocumentController] currentDocument] 
setValue:newBg
                                                                        forKeyPath:@"docPrefsController.selection.bgImage"];    

       // finally, make the requested change on the copy
       [newBg setValue:value forKeyPath:keyPath];
   } else {
       [super setValue:value forKeyPath:keyPath];
   }
}

Related mailsAuthorDate
mlStrategy for read only Templates with Core Data George Orthwein Jun 2, 18:04
mlRe: Strategy for read only Templates with Core Data George Orthwein Jun 5, 20:35
mlRe: Strategy for read only Templates with Core Data George Orthwein Jun 5, 23:13
mlRe: Strategy for read only Templates with Core Data mmalcolm crawford Jun 18, 06:25
mlRe: Strategy for read only Templates with Core Data George Orthwein Jun 19, 07:55