Skip to content

Instantly share code, notes, and snippets.

@rentzsch
Created October 4, 2011 01:54
Show Gist options
  • Save rentzsch/1260737 to your computer and use it in GitHub Desktop.
Save rentzsch/1260737 to your computer and use it in GitHub Desktop.
#import <Foundation/Foundation.h>
@interface TestableUserDefaults : NSObject {
NSString *storage;
}
@property (retain) NSString *storage;
+ (id)defaults;
- (NSArray *)arrayForKey:(NSString *)defaultName;
- (void)setObject:(id)value forKey:(NSString *)defaultName;
- (BOOL)synchronize;
@end
#import "TestableUserDefaults.h"
#import "NSDate+JRExtensions.h"
@interface TestableUserDefaults ()
- (NSMutableDictionary*)plist;
- (void)setPlist:(NSMutableDictionary*)plist;
@end
@implementation TestableUserDefaults
@synthesize storage;
+ (id)defaults {
return [[[self alloc] init] autorelease];
}
- (void)dealloc {
[storage release];
[super dealloc];
}
- (NSString*)description {
return [NSString stringWithFormat:@"%@<%p>:\n%@", [self className], self, self.storage];
}
- (NSMutableDictionary*)plist {
NSMutableDictionary *result = nil;
if (self.storage) {
NSPropertyListFormat format = NSPropertyListXMLFormat_v1_0;
NSError *error = nil;
result = [NSPropertyListSerialization propertyListWithData:[self.storage dataUsingEncoding:NSUTF8StringEncoding]
options:0
format:&format
error:&error];
if (!result && error) {
NSLog(@"plist error: %@ %@ %@", error, [error userInfo]);
}
}
return result;
}
- (void)setPlist:(NSMutableDictionary*)plist {
NSError *error = nil;
NSData *data = [NSPropertyListSerialization dataWithPropertyList:plist
format:NSPropertyListXMLFormat_v1_0
options:0
error:&error];
if (!data && error) {
NSLog(@"setPlist error: %@ %@ %@", error, [error userInfo], plist);
}
self.storage = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
}
- (NSArray *)arrayForKey:(NSString *)defaultName {
NSMutableDictionary *plist = [self plist];
NSArray *result = [plist objectForKey:defaultName];
return result;
}
- (void)setObject:(id)value forKey:(NSString *)defaultName {
NSMutableDictionary *plist = [self plist];
if (plist) {
[plist setObject:value forKey:defaultName];
} else {
plist = [NSDictionary dictionaryWithObject:value forKey:defaultName];
}
[self setPlist:plist];
}
- (BOOL)synchronize {
return YES;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment