Skip to content

Instantly share code, notes, and snippets.

@ethanmick
Created April 18, 2013 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ethanmick/5415081 to your computer and use it in GitHub Desktop.
Save ethanmick/5415081 to your computer and use it in GitHub Desktop.
Persisting a CMUser subclass.
//
// KPUser.h
// Header File
//
#import <CloudMine/CloudMine.h>
@interface KPUser : CMUser
@property (nonatomic, copy) NSString *firstName;
@property (nonatomic, copy) NSString *lastName;
- (void)persist;
+ (KPUser *)getPersistedUser;
@end
//
// KPUser.m
// Implementation File
//
#import "KPUser.h"
NSString *const FirstNameKey = @"firstName";
NSString *const LastNameKey = @"lastName";
NSString *const UserPersistanceKey = @"com.cloudmine.kpuser";
@implementation KPUser
- (void)encodeWithCoder:(NSCoder *)aCoder {
[super encodeWithCoder:aCoder];
[aCoder encodeObject:self.firstName forKey:FirstNameKey];
[aCoder encodeObject:self.lastName forKey:LastNameKey];
}
- (id) initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
self.firstName = [aDecoder decodeObjectForKey:FirstNameKey];
self.lastName = [aDecoder decodeObjectForKey:LastNameKey];
}
return self;
}
+ (KPUser *)getPersistedUser {
KPUser *user = nil;
NSData *userData = [[NSUserDefaults standardUserDefaults] objectForKey:UserPersistanceKey];
if (userData) {
user = [NSKeyedUnarchiver unarchiveObjectWithData:userData];
} else {
///
/// No User found...
///
return nil;
}
// Set this user as the user of the default store
CMStore *store = [CMStore defaultStore];
store.user = user;
return user;
}
- (void)persist {
[[CMStore defaultStore] setUser:self];
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:self] forKey:UserPersistanceKey];
[[NSUserDefaults standardUserDefaults] synchronize];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment