好的,上周我已经超过了一百万次,但我就是不明白。(是的,我读过 Apple 的文档。)
我正在归档我的对象,它似乎正在正确归档(我可以看到写入文件系统的文件,如果我检查它,我可以在其中看到我的数据)。但是,当我重新启动我的应用程序时,我的数据没有被恢复。我读到的每个例子都告诉我这是多么容易,但我就是不明白。一个独特的事情是我的对象是一个单例,它用于在视图控制器之间传递数据。
我真的很感激一些明智的建议。提前致谢。
这是我的标题:
#import <Foundation/Foundation.h>
@interface SharedAppDataObject : NSObject <NSCoding>
{
NSMutableDictionary *apiKeyDictionary;
NSString *skuFieldText;
NSIndexPath *checkmarkIndex;
}
+ (SharedAppDataObject *)sharedStore;
@property (nonatomic, copy) NSString *skuFieldText;
@property (nonatomic, copy) NSIndexPath *checkmarkIndex;
@property (nonatomic, copy) NSMutableDictionary *apiKeyDictionary;
-(void)setValue:(NSString *)apiKey forKey:(NSString *)name;
-(void)setSkuField:(NSString *)s;
-(void)setCheckmarkIndex:(NSIndexPath *)p;
-(NSMutableDictionary *)apiKeyDictionary;
-(BOOL)saveChanges;
@end
这是我的实现:
#import "SharedAppDataObject.h"
@implementation SharedAppDataObject
@synthesize skuFieldText;
@synthesize checkmarkIndex;
@synthesize apiKeyDictionary;
//create our shared singleton store
+(SharedAppDataObject *)sharedStore {
static SharedAppDataObject *sharedStore = nil;
if (!sharedStore) {
sharedStore = [NSKeyedUnarchiver unarchiveObjectWithFile:[SharedAppDataObject archivePath]];
if(!sharedStore)
sharedStore = [[super allocWithZone:NULL] init];
}
return sharedStore;
}
-(id) init {
self = [super init];
if (self) {
}
return self;
}
-(void)setValue:(id)apiKey forKey:(NSString *)name {
[apiKeyDictionary setObject:apiKey forKey:name];
}
-(void)setSkuField:(NSString *)s {
skuFieldText = s;
}
-(NSMutableDictionary *)apiKeyDictionary {
return apiKeyDictionary;
}
-(void)setCheckmarkIndex:(NSIndexPath *)p {
checkmarkIndex = p;
}
-(void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:skuFieldText forKey:@"skuFieldText"];
[aCoder encodeObject:checkmarkIndex forKey:@"checkmarkIndex"];
[aCoder encodeObject:apiKeyDictionary forKey:@"apiKeyDictionary"];
}
-(id)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
[self setSkuFieldText:[aDecoder decodeObjectForKey:@"skuFieldText"]];
[self setCheckmarkIndex:[aDecoder decodeObjectForKey:@"checkmarkIndex"]];
[self setApiKeyDictionary:[aDecoder decodeObjectForKey:@"apiKeyDictionary"]];
}
return self;
}
+(NSString *)archivePath {
NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [documentDirectories objectAtIndex:0];
return [documentDirectory stringByAppendingPathComponent:@"bbyo.archive"];
}
-(BOOL)saveChanges {
return [NSKeyedArchiver archiveRootObject:self toFile:[SharedAppDataObject archivePath]];
}
@end
来自 App Delegate 的保存方法:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
BOOL success = [[SharedAppDataObject sharedStore] saveChanges];
if (success) {
NSLog(@"Saved all the data");
} else {
NSLog(@"Didn't save any of the data");
}
}