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
184 views
in Technique[技术] by (71.8m points)

ios - How can I decode an object when original class is not available?

I have an iOS 7 application that saves a custom object to app's iCloud Docs folder as a file. For this, I make use of NSCoding protocol.

@interface Person : NSObject <NSCoding>

    @property (copy, nonatomic) NSString *name
    @property (copy, nonatomic) NSString *lastName

@end

Object serialization works perfectly in iOS 7 version of the app:

  1. initWithCoder and encodeWithCoder

  2. [NSKeyedArchiver archivedDataWithRootObject:person]

  3. person = NSKeyedUnarchiver unarchiveObjectWithData:(NSData *)theData]

But I need to move this app to iOS 8, and this class will be coded in swift and 'renamed' for this new iOS 8 version of the app.

class PersonOldVersion: NSObject, NSCoding {
    var name = ""
    var lastName = ""
}

When I try to unarchive the object I got the following error:

*** Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: '*** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (Person)'

I already tried renaming swift class 'PersonOldVersion' to original class name ('Person') but still fails.

How can I decode an object which original class isn't available?

question from:https://stackoverflow.com/questions/25492158/how-can-i-decode-an-object-when-original-class-is-not-available

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

1 Reply

0 votes
by (71.8m points)

This might be another solution, and it's what I did (since I didn't use Swift at that time).

In my case, I archived an object of class "City" but then renamed the class to "CityLegacy" because I created a completely new "City" class.

I had to do this to unarchive the old "City" object as a "CityLegacy" object:

// Tell the NSKeyedUnarchiver that the class has been renamed
[NSKeyedUnarchiver setClass:[CityLegacy class] forClassName:@"City"];

// Unarchive the object as usual
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [defaults objectForKey:@"city"];
CityLegacy *city = [NSKeyedUnarchiver unarchiveObjectWithData:data];

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

...