Database Reference
In-Depth Information
-setValue:forUndefinedKey:
CDPreferences/DocumentPreferences.m
- ( void )setValue:(id)value forUndefinedKey:(NSString*)key
{
[self willChangeValueForKey:key];
NSManagedObject *parameter = [self findParameter:key];
if (!parameter) {
if ([[self defaults] valueForKey:key] &&
[value isEqualTo:[[self defaults] valueForKey:key]]) {
[self didChangeValueForKey:key];
return ;
}
parameter = [self createParameter:key];
} else {
if ([[self defaults] valueForKey:key] &&
[value isEqualTo:[[self defaults] valueForKey:key]]) {
[self willChangeValueForKey:key];
[[[self associatedDocument] managedObjectContext] deleteObject:parameter];
[self didChangeValueForKey:key];
return ;
}
}
if ([value isKindOfClass:[NSNumber class]]) {
[parameter setValue:[value stringValue] forKey:@ "value" ];
} else if ([value isKindOfClass:[NSDate class]]) {
[parameter setValue:[value description] forKey:@ "value" ];
} else {
[parameter setValue:value forKey:@ "value" ];
}
[self didChangeValueForKey:key];
}
In addition to being able to access a parameter, we also need to set parameters.
This is done in the counterpart method of -valueForUndefinedKey: called -setVal-
ue:forUndefinedKey: . In this method, we first notify the system we are going to be
changing the value associated with the passed-in key. This is part of KVO and
is required so that notifications work correctly. After starting the KVO notifi-
cation, we attempt to retrieve the NSManagedObject from the parameters table.
If there is no NSManagedObject for the passed-in key, we check the defaults
NSDictionary to see whether there is a default. If there is a default set and the
passed-in value matches the default, we complete the KVO notification and
return. If the default value does not match the passed-in value, we create a
new NSManagedObject for the passed-in key.
If there is an NSManagedObject and a default set for the key, we compare the
default value to the passed-in value. If they match, we delete the NSManagedOb-
ject , which effectively resets the parameter to the default. Once we pass the
 
 
 
Search WWH ::




Custom Search