我无法弄清楚如何让存档在 iOS 5 应用程序中工作。我有一个单例 SessionStore,如果它在初始化时存在,我想检索它。SessionStore 继承自 NSObject 并有一个 ivar,一个 NSMutableArray *allSessions,我想从 plist 文件中加载它。这是 SessionStore.m 不确定问题是否明显或者您是否需要更多信息......谢谢!弥敦道
#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;
}
在 AppDelegate.m 中,它在终止时保存 plist 文件:
- (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];
}