好吧,我上週已經過了這一百萬次了,而我卻沒有得到它。 (是的,我讀過蘋果的文檔。)無法恢復歸檔數據
我歸檔我的對象,它似乎正在歸檔正確(我可以看到文件寫入文件系統,如果我檢查它,我可以看到我的數據)。但是,當我重新啓動我的應用程序時,我的數據未被恢復。我讀過的每個例子告訴我這是多麼容易,但我只是沒有得到它。唯一的一點是我的對象是一個單例,它用於在視圖控制器之間傳遞數據。
我真的很感謝一些賢者的建議。提前致謝。
這裏是我的頭:
#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
保存方法:
- (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");
}
}
您鏈接到的例子是完美的。謝謝! – Selch