1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
|
#import <Foundation/Foundation.h>
#import "NSColor+SimpleAgenda.h"
#import "ConfigManager.h"
NSString * const SAConfigManagerValueChanged = @"SAConfigManagerValueChanged";
static ConfigManager *singleton;
static NSUserDefaults *appDefaults;
@implementation ConfigManager
+ (void)initialize
{
if ([ConfigManager class] == self) {
singleton = [ConfigManager new];
appDefaults = [NSUserDefaults standardUserDefaults];
}
}
+ (ConfigManager *)globalConfig
{
return singleton;
}
- (id)init
{
if ((self = [super init]))
_defaults = [NSMutableDictionary new];
return self;
}
- (id)initForKey:(NSString *)key
{
if ((self = [self init]))
ASSIGNCOPY(_key, key);
return self;
}
- (void)dealloc
{
DESTROY(_defaults);
DESTROY(_key);
[super dealloc];
}
- (void)registerDefaults:(NSDictionary *)defaults
{
[_defaults addEntriesFromDictionary:defaults];
}
- (id)objectForKey:(NSString *)key
{
id value = _key ? [[appDefaults dictionaryForKey:_key] objectForKey:key] : [appDefaults objectForKey:key];
return value ? value : [_defaults objectForKey:key];
}
- (void)removeObjectForKey:(NSString *)key
{
NSMutableDictionary *mdict;
if (_key) {
mdict = [NSMutableDictionary dictionaryWithDictionary:[appDefaults objectForKey:_key]];
[mdict removeObjectForKey:key];
[appDefaults setObject:mdict forKey:_key];
[[NSNotificationCenter defaultCenter] postNotificationName:SAConfigManagerValueChanged
object:self
userInfo:[NSDictionary dictionaryWithObject:_key forKey:@"key"]];
} else
[appDefaults removeObjectForKey:key];
[appDefaults synchronize];
}
- (void)setObject:(id)value forKey:(NSString *)key
{
NSMutableDictionary *mdict;
if (_key) {
mdict = [NSMutableDictionary dictionaryWithDictionary:[appDefaults objectForKey:_key]];
[mdict setObject:value forKey:key];
[appDefaults setObject:mdict forKey:_key];
} else
[appDefaults setObject:value forKey:key];
[[NSNotificationCenter defaultCenter] postNotificationName:SAConfigManagerValueChanged
object:self
userInfo:[NSDictionary dictionaryWithObject:key forKey:@"key"]];
[appDefaults synchronize];
}
- (int)integerForKey:(NSString *)key
{
id object = [self objectForKey:key];
if (object != nil)
return [object intValue];
return 0;
}
- (void)setInteger:(int)value forKey:(NSString *)key
{
[self setObject:[NSNumber numberWithInt:value] forKey:key];
}
- (NSColor *)colorForKey:(NSString *)key
{
id obj = [self objectForKey:key];
if ([obj isKindOfClass:[NSData class]])
return [NSUnarchiver unarchiveObjectWithData:obj];
return [NSColor colorFromString:obj];
}
- (void)setColor:(NSColor *)value forKey:(NSString *)key
{
[self setObject:[value description] forKey:key];
}
@end
|