Created
February 23, 2015 02:10
-
-
Save armadsen/3f3023525bb96f5c2070 to your computer and use it in GitHub Desktop.
PersonController for DevMountain Lesson 13
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
// For PersonController.h: | |
#import "Person.h" | |
@interface PersonController : NSObject | |
@property (nonatomic, strong, readonly) NSArray *personList; | |
+ (PersonController *)sharedInstance; | |
- (void)addPerson:(Person *)person; | |
- (void)removePerson:(Person *)person; | |
@end | |
// For PersonController.m: | |
static NSString * const personListKey = @"personList"; | |
@interface PersonController () | |
@property (nonatomic, strong) NSArray *personList; | |
@end | |
@implementation PersonController | |
+ (PersonController *)sharedInstance { | |
static PersonController *sharedInstance = nil; | |
static dispatch_once_t onceToken; | |
dispatch_once(&onceToken, ^{ | |
sharedInstance = [[PersonController alloc] init]; | |
sharedInstance.personList = [PersonController loadPersonListFromDefaults]; | |
}); | |
return sharedInstance; | |
} | |
- (void)addPerson:(Person *)person { | |
if (!person) { | |
return; | |
} | |
NSMutableArray *mutablePersonList = [[NSMutableArray alloc] initWithArray:self.personList]; | |
[mutablePersonList addObject:person]; | |
self.personList = mutablePersonList; | |
} | |
- (void)removePerson:(Person *)person { | |
if (!person) { | |
return; | |
} | |
NSMutableArray *mutablePersonList = self.personList.mutableCopy; | |
[mutablePersonList removeObject:person]; | |
self.personList = mutablePersonList; | |
} | |
+ (NSMutableArray *)loadPersonListFromDefaults { | |
NSArray *personDictionaries = [[NSUserDefaults standardUserDefaults] objectForKey:personListKey]; | |
NSMutableArray *personList = [NSMutableArray new]; | |
for (NSDictionary *personDictionary in personDictionaries) { | |
Person *person = [[Person alloc] initWithDictionary:personDictionary]; | |
[personList addObject:person]; | |
} | |
return personList; | |
} | |
+ (void)storePersonListInDefaults:(NSArray *)personList { | |
NSMutableArray *personDictionaries = [NSMutableArray new]; | |
for (Person *person in personList) { | |
[personDictionaries addObject:[person personDictionary]]; | |
} | |
[[NSUserDefaults standardUserDefaults] setObject:personDictionaries forKey:personListKey]; | |
[[NSUserDefaults standardUserDefaults] synchronize]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment