memento objective c
-
I want to realise mymento's paththern. My problem is that I want to keep the game even when the laser shuts the game. Now, I need to keep the Object...deck a little corny.
- (void)saveCurrentState { [[NSUserDefaults standardUserDefaults] setObject:_deck forKey:@"currentDeck"]; NSLog(@"save"); }
- (void)loadPreviousState
{
_deck = [[NSUserDefaults standardUserDefaults] objectForKey:@"currentDeck"];
[self updateCardWrapForAllCards];
NSLog(@"load");
}
created notification
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(saveCurrentState) name:UIApplicationDidEnterBackgroundNotification object:nil];
Well, now that I'm going to the back of the granite, that's what's going on. Thank you.
- (void)loadPreviousState
-
In the deck class, you need to write two methods below (replace all objects from your class)
- (void)encodeWithCoder:(NSCoder *)encoder { //Encode properties, other class variables, etc [encoder encodeObject:self.question forKey:@"question"]; [encoder encodeObject:self.categoryName forKey:@"category"]; [encoder encodeObject:self.subCategoryName forKey:@"subcategory"]; }
- (id)initWithCoder:(NSCoder *)decoder {
if((self = [super init])) {
//decode properties, other class vars
self.question = [decoder decodeObjectForKey:@"question"];
self.categoryName = [decoder decodeObjectForKey:@"category"];
self.subCategoryName = [decoder decodeObjectForKey:@"subcategory"];
}
return self;
}
Read and record in the user defaults:
- (void)saveCustomObject:(MyObject *)object key:(NSString *)key {
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:encodedObject forKey:key];
[defaults synchronize];}
- (MyObject *)loadCustomObjectWithKey:(NSString *)key {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *encodedObject = [defaults objectForKey:key];
MyObject *object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
return object;
}
The code is down. https://stackoverflow.com/questions/2315948/how-to-store-custom-objects-in-nsuserdefaults
- (id)initWithCoder:(NSCoder *)decoder {