我正在尝试使用 NSCoding 从我的应用程序中保存一些值。我能够保存该值但无法检索它。
这是我声明协议的地方:
@interface AddReminderEventViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource, NSCoding>
这是我遵守协议的地方:
-(void)encodeWithCoder:(NSCoder *)enCoder
{
[enCoder encodeObject:self.eventRepeatDurationDate forKey:kEventRepeatDuration];
[enCoder encodeObject:self.eventIDsMutableArray forKey:kEventIDsMutableArray];
[enCoder encodeObject:self.eventRepeatDurationString forKey:@"mytest"];}
和这里:
-(id)initWithCoder:(NSCoder *)decoder {
if (self = [super init]){
self.eventRepeatDurationDate = [[decoder decodeObjectForKey:kEventRepeatDuration] retain];
self.eventIDsMutableArray = [[decoder decodeObjectForKey:kEventIDsMutableArray] retain];
self.eventRepeatDurationString = [[decoder decodeObjectForKey:@"mytest"] retain];} return self; }
这里是我调用归档和取消归档方法的地方:
[self saveDataToDisk];
[self loadDataFromDisk];
以下是这些方法的主体及其 NSLog 内容:
- (void)saveDataToDisk {
NSString *reminderEventIDsPathString = @"~/Library/Application Support/ReminderIDs.archive";
//reminderEventIDsPathString = @"~/Library/Application Support/ReminderIDs.archive";
reminderEventIDsPathString = [reminderEventIDsPathString stringByExpandingTildeInPath];
NSLog(@"WATCH1: reminderEventIDsPathString is %@", reminderEventIDsPathString);
NSMutableDictionary *rootObject;
rootObject = [NSMutableDictionary dictionary];
[rootObject setValue:eventRepeatDurationString forKey:@"mytest"];
NSLog(@"1rootObject IS %@", rootObject);
[NSKeyedArchiver archiveRootObject:rootObject toFile:reminderEventIDsPathString];}
reminderEventIDsPathString is /Users/tester/Library/Application Support/iPhone Simulator/5.0/Applications/E26D57DE-C4E1-4318-AEDD-7207F41010A9/Library/Application Support/ReminderIDs.archive
2012-01-16 15:47:48.578 [29658:15503] 1rootObject IS {mytest = 7;}
这是解压缩代码及其 NSLog 内容:
- (void)loadDataFromDisk {
NSString *testValue = [[NSString alloc] init];
NSString *reminderEventIDsPathString = @"~/Library/Application Support/ReminderIDs.archive";
reminderEventIDsPathString = [reminderEventIDsPathString stringByExpandingTildeInPath];
NSLog(@"WATCH2: reminderEventIDsPathString is %@", reminderEventIDsPathString);
NSMutableDictionary *rootObject;
rootObject = [[NSKeyedUnarchiver unarchiveObjectWithFile:reminderEventIDsPathString] retain];
NSLog(@"2rootObject IS %@", rootObject);
NSLog(@"WATCH3 - %@", [rootObject objectForKey:@"mytest" ]);
if ([rootObject valueForKey:@"mytest"]) {
testValue = [rootObject valueForKey:@"mytest"];
NSLog(@"WATCH: testValue is %@", testValue); } }
2012-01-16 15:48:14.965 [29658:15503] WATCH2: reminderEventIDsPathString is /Users/tester/Library/Application Support/iPhone Simulator/5.0/Applications/E26D57DE-C4E1-4318-AEDD-7207F41010A9/Library/Application Support/ReminderIDs.archive
2012-01-16 15:48:17.879 [29658:15503] 2rootObject IS (null)
我无法取消归档内容,我错过了什么?我只是专注于我的编码器/解码器方法中最简单的值,只是为了测试它,但我什至无法让字符串值工作。
谢谢