I am storing keyboard shortcuts represented as NSDictionary
instances into user defaults and have some trouble representing “none” values. When my application starts I register some default shortcuts. Then the user may change keyboard shortcuts in application preferences. The keyboard setting widgets are bound directly to user defaults.
The user may click a special “clear” button that clears a keyboard shortcut, meaning that user does not wish to set a shorcut f开发者_如何学Pythonor given feature. When the keyboard shortcut is cleared, it’s set to nil
. This is a problem, because setting the shortcut to nil
in user defaults reverts the value to the one registered with registerDefaults:
. (The objectForKey:
method does not find given key in the app domain and therefore goes into the NSRegistrationDomain
domain.)
How should I represent the “cleared” keyboard shortcuts so that objectForKey:
returns nil
? Do I have to play games with empty NSDictionary
instances and other sentinel values, or is there a better way?
I ended up using this transformer:
@interface NullTransformer : NSValueTransformer {}
@end
@implementation NullTransformer
+ (BOOL) allowsReverseTransformation {
return YES;
}
- (id) transformedValue: (id) value {
return [value count] ? value : nil;
}
- (id) reverseTransformedValue: (id) value {
return value ? value : [NSDictionary dictionary];
}
@end
In other words, I use an empty dictionary to represent unset values and convert between this special value and nil
using a custom transformer so that my classes don’t have to care. It’s not perfect, but seems like a tolerable solution.
精彩评论