i am on objective-c, macOS not iOS.
I have an app that currently saves data by writing NSData to a path like this:
GlobalAppData * dataToSave = self.data; // based on NSObject supporting NSSecureCoding
NSKeyedArchiver* archiver=[[NSKeyedArchiver alloc] initRequiringSecureCoding:YES];
[archiver encodeObject:dataToSave forKey:@"global"];
NSData* data = [archiver encodedData];
[data writeToFile:somefilePath
atomically:YES];
User can double click the file and that triggeres loading. Basically NSDocument is used for supporting custom document but loading/saving is handled by the app as former concept didn't use multiple documents (just single). Loading code is this:
NSError* err;
NSData* data = [NSData dataWithContentsOfURL:projectURL options:NSDataReadingMappedIfSafe error:&err];
NSKeyedUnarchiver* unarchiver = [[NSKeyedUnarchiver alloc] initForReadingFromData:data error:&err];
When i try to read the data it works as expected:
GlobalAppData * myData = [unarchiver decodeObjectForKey:@"global"];
Now i have switched to DOCUMENT based structure with multiple documents allowed. I implemented saving and loading according to NSDocument. Loading is now handled like this in a NSDocument subclass:
- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError {
NSKeyedUnarchiver* unarchiver = [[NSKeyedUnarchiver alloc] initForReadingFromData:data error:outError];
// Load appData
GlobalAppData* appData = [unarchiver decodeObjectOfClass:[GlobalAppData class] forKey:@"global"];
...
Now when i WRITE and LOAD data with the new (document-)code, everything works fine.
What does NOT work is loading an old file (NSData* manually written with the methods at top).
appData is always nil.
I want to provide some kind of backwards compatibility. What would be the right approach to do so? What am i missing here?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…