Taking @chrissr's answer and running with it, this code can be implemented into a nice category on NSUserDefaults
to save and retrieve custom objects:
@interface NSUserDefaults (NSUserDefaultsExtensions)
- (void)saveCustomObject:(id<NSCoding>)object
key:(NSString *)key;
- (id<NSCoding>)loadCustomObjectWithKey:(NSString *)key;
@end
@implementation NSUserDefaults (NSUserDefaultsExtensions)
- (void)saveCustomObject:(id<NSCoding>)object
key:(NSString *)key {
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
[self setObject:encodedObject forKey:key];
[self synchronize];
}
- (id<NSCoding>)loadCustomObjectWithKey:(NSString *)key {
NSData *encodedObject = [self objectForKey:key];
id<NSCoding> object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
return object;
}
@end
Usage:
[[NSUserDefaults standardUserDefaults] saveCustomObject:myObject key:@"myKey"];