I'm having trouble figuring out how to get the archiving to work in an iOS 5 app. I have a singleton SessionStore that I'd like to retrieve plist data if it exists upon initialization. SessionStore inherits from NSObject and has one ivar, an NSMutableArray *allSessions, which I want to load from the plist file. Here's the SessionStore.m Not sure if the problem is obvious or if you need more info... thanks! Nathan
#import "SessionStore.h"
static SessionStore *defaultStore = nil;
@implementation SessionStore
+(SessionStore *)defaultStore {
if (!defaultStore) {
// Load data.plist if it exists
NSString *pathInDocuments = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"data.plist"];
NSFileManager *fileManager = [[NSFileManager alloc] init];
if ([fileManager fileExistsAtPath:pathInDocuments])
defaultStore = [NSKeyedUnarchiver unarchiveObjectWithFile:pathInDocuments];
} else
defaultStore = [[super allocWithZone:NULL] init];
return defaultStore;
}
+(id)allocWithZone:(NSZone *)zone {
return [self defaultStore];
}
-(id)init {
if (defaultStore)
return defaultStore;
self = [super init];
if (self)
allSessions = [[NSMutableArray alloc] init];
return self;
}
-(NSMutableArray *)allSessions {
if (!allSessions) allSessions = [[NSMutableArray alloc] init];
return allSessions;
}
-(void)setAllSessions:(NSMutableArray *)sessions {
allSessions = sessions;
}
-(void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:allSessions forKey:@"All Sessions"];
}
-(id)initWithCoder:(NSCoder *)aDecoder {
self = [SessionStore defaultStore];
[self setAllSessions:[aDecoder decodeObjectForKey:@"All Sessions"]];
return self;
}
In AppDelegate.m it saves the plist file upon terminating:
- (void)applicationWillTerminate:(UIApplication *)application
{
// Save data to plist file
NSString *pathInDocuments = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"data.plist"];
[NSKeyedArchiver archiveRootObject:[SessionStore defaultStore] toFile:pathInDocuments];
}