What If
The biggest "what if" on this design is...what if you want to limit what parameters can be stored? To handle that situation, an additional method is required—as well as a static variable. First the static variable:
static NSArray *validParameterNames; + (void)initialize { validParameterNames = [NSArray arrayWithObjects:@"parameter1", @"parameter2", @"parameter3", nil]; [validParameterNames retain]; }
In the initialize method of the NSDocument subclass, I have created an array of valid parameter names. If you need to add more parameters to the document, simply add their names here.
The second step is to validate a parameter name:
- (BOOL)parameterIsValid:(NSString *)name { return [validParameterNames containsObject:name]; }
This method will check against the array for the passed-in parameter name. If the name exists, it will return YES; otherwise it will return NO.
With these methods in place, the following line would get added to the top of both the valueForUndefinedKey: method and the setValue:forUndefinedKey: method:
if (![self parameterIsValid:key]) [[NSException exceptionWithName:NSUndefinedKeyException reason:[NSString stringWithFormat:@"Unknown key:%@", key] userInfo:nil] raise];
After this conditional is in place, an exception will be thrown if the program attempts to set or retrieve a parameter that does not exist.