Created
April 18, 2013 18:30
-
-
Save ethanmick/5415081 to your computer and use it in GitHub Desktop.
Persisting a CMUser subclass.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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