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

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


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 usualNSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];NSData *data = [defaults objectForKey:@"city"];CityLegacy *city = [NSKeyedUnarchiver unarchiveObjectWithData:data];


If the name of the class in Objective-C is important, you need to explicitly specify the name. Otherwise, Swift will provide some mangled name.

@objc(Person)class PersonOldVersion: NSObject, NSCoding {    var name = ""    var lastName = ""}


Here's a Swift translation for Ferran Maylinch's answer above.

Had a similar problem in a Swift project after I duplicated the original target in order to have 2 builds of my product. The 2 builds needed to be useable interchangeably.

So, I had something like myapp_light.app and my app_pro.app. Setting the class fixed this issue.

NSKeyedUnarchiver.setClass(MyClass1.classForKeyedUnarchiver(), forClassName: "myapp_light.MyClass1")NSKeyedUnarchiver.setClass(MyClass1.classForKeyedUnarchiver(), forClassName: "myapp_pro.MyClass1")if let object:AnyObject = NSKeyedUnarchiver.unarchiveObjectWithFile("\path\...") {    var myobject = object as! Dictionary<String,MyClass1>    //-- other stuff here}