Я пытаюсь сохранить свой граф объектов в файл, а затем перезагрузить его позже, однако decodeObjectForKey: всегда возвращает nil для любого ключа, который я указываю.
Создается двоичный файл, в котором есть текст, читаемый человеком, т. Е. TitleTextColor, поэтому я думаю, что процесс архивации работает.
Я не понял, как работают NSKeyedArchiver и NSKeyedUnarchiver? Любая помощь будет оценена.
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeFloat:titleFontSize forKey:@"titleFontSize"];
[encoder encodeObject:[UIColor orangeColor] forKey:@"titleTextColor"];
[encoder encodeObject:lineSeparatorColor forKey:@"lineSeparatorColor"];
[encoder encodeObject:bodyTextColor forKey:@"bodyTextColor"];
[encoder encodeFloat:bodyTextFontSize forKey:@"bodyTextFontSize"];
[encoder encodeObject:backgroundColor forKey:@"backgroundColor"];
[encoder encodeObject:tintColor forKey:@"tintColor"];
[encoder encodeInteger:bodyTextAlignment forKey:@"bodyTextAlignment"];
[encoder encodeObject:@"Text" forKey:@"Text"];
}
+ (void) saveToFile {
// Get the shared instance
PSYDefaults *sharedInstance = [PSYDefaults sharedInstance];
// Serialise the object
NSData *serializedObject = [NSKeyedArchiver archivedDataWithRootObject:sharedInstance];
// Get the path and filename of the file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pathAndFileName = [documentsDirectory stringByAppendingPathComponent:ksDefaultsFileName];
// Write the defaults to a file
if (serializedObject) [serializedObject writeToFile:pathAndFileName atomically:YES];
}
+ (void) loadFromFile {
// Get the shared instance
PSYDefaults *sharedInstance = [PSYDefaults sharedInstance];
// Get the path and filename of the file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pathAndFileName = [documentsDirectory stringByAppendingPathComponent:ksDefaultsFileName];
NSData *codedData = [[[NSData alloc] initWithContentsOfFile:pathAndFileName] autorelease];
NSKeyedUnarchiver *defaults = [[NSKeyedUnarchiver alloc] initForReadingWithData:codedData];
// Set the properties of the shared instance
NSString *test = [defaults decodeObjectForKey:@"Text"];
NSLog (@"%@", test);
sharedInstance.titleTextColor = [defaults decodeObjectForKey:@"titleTextColor"];
[defaults release];
}
РЕДАКТИРОВАТЬ: на основе рекомендаций DarkDust:
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
self.titleFontSize = [[aDecoder decodeObjectForKey:@"titleFontSize"] floatValue];
self.titleTextColor = [aDecoder decodeObjectForKey:@"titleTextColor"];
self.lineSeparatorColor = [aDecoder decodeObjectForKey:@"lineSeparatorColor"];
self.bodyTextColor = [aDecoder decodeObjectForKey:@"bodyTextColor"];
self.bodyTextFontSize = [[aDecoder decodeObjectForKey:@"bodyTextFontSize"] floatValue];
self.backgroundColor = [aDecoder decodeObjectForKey:@"backgroundColor"];
self.tintColor = [aDecoder decodeObjectForKey:@"tintColor"];
self.bodyTextAlignment = [[aDecoder decodeObjectForKey:@"bodyTextAlignment"] intValue];
}
return self;
}
и создание нового экземпляра просто для проверки:
+ (void) loadFromFile {
// Get the shared instance
PSYDefaults *sharedInstance = [PSYDefaults sharedInstance];
// Get the path and filename of the file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pathAndFileName = [documentsDirectory stringByAppendingPathComponent:ksDefaultsFileName];
NSData *codedData = [[[NSData alloc] initWithContentsOfFile:pathAndFileName] autorelease];
PSYDefaults *newInstance = [NSKeyedUnarchiver unarchiveObjectWithData:codedData];
sharedInstance.titleTextColor = newInstance.titleTextColor;
}
РЕДАКТИРОВАТЬ - Обновление (необходимо для кодирования чисел и чисел в виде NSNumbers)
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:[NSNumber numberWithFloat:titleFontSize] forKey:@"titleFontSize"];
[encoder encodeObject:titleTextColor forKey:@"titleTextColor"];
[encoder encodeObject:lineSeparatorColor forKey:@"lineSeparatorColor"];
[encoder encodeObject:bodyTextColor forKey:@"bodyTextColor"];
[encoder encodeObject:[NSNumber numberWithFloat:bodyTextFontSize] forKey:@"bodyTextFontSize"];
[encoder encodeObject:backgroundColor forKey:@"backgroundColor"];
[encoder encodeObject:tintColor forKey:@"tintColor"];
[encoder encodeObject:[NSNumber numberWithInt:bodyTextAlignment] forKey:@"bodyTextAlignment"];
}