Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

objective c - NSDataFromURL different to NSData from NSDocument?

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...