问题
- I have 2 Targets of my IOS-App : MYAPPTARGET_1 & MYAPPTARGET_2
- MYAPPTARGET_1 is writing a Stream to a BLOB using NSKeyedArchiver
- MYAPPTARGET_2 is reading a Stream from a BLOB using NSKeyedUnarchiver
When unarchiving the Stream from the BLOB in my MYAPPTARGET_2, I get the Error: 016-01-18 15:01:38.541 WorldHistoryAtlasTest[598:9405] * Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: '* -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (MYAPPTARGET_1.MapTheme) for key (rootobject);
So it seemes to be obviously encoded with a prefix of MYAPPTARGET_1 and is not readable from MYAPPTARGET_2.
So I got a hint for overcome this in another STACKOVERFLOW Answer to use a delegate unarchiver to overwrite the Classname. But I am not able to implement this:
func unarchiver(unarchiver: NSKeyedUnarchiver, cannotDecodeObjectOfClassName name: String, originalClasses classNames: [String]) -> AnyClass? {
print("ClassName is " + name);
return nil; // WHAT TO DO , TO OVERWRITE THE CLASS NAME.
}
var mykeyedunarchiver:NSKeyedUnarchiver=NSKeyedUnarchiver(forReadingWithData: data!);
mykeyedunarchiver.delegate = self;
let temp=mykeyedunarchiver.decodeObjectForKey("rootobject")
I have an App with targetname MYAPPTARGET_1 and I store some data as blob using the NSKeyedArchiver feature.
Then later with a second Apps-Target named MYAPPTARGET_2 I try to read the data again. Load from the BLOB stored in the DB.
I would be so happy if someone could give me a practical hint on this.
回答1:
the following is enough:
class MyObject: NSObject, NSCoding {...}
let my = MyObject()
// archive
NSKeyedArchiver.setClassName("MyObject", for: MyObject.self)
let data = NSKeyedArchiver.archivedData(withRootObject: r)
// unarchive
NSKeyedUnarchiver.setClass(MyObject.self, forClassName: "MyObject")
let _ = NSKeyedUnarchiver.unarchiveObject(with: data)
this helped me to exchange custom objects between a mac-app and an iphone app
来源:https://stackoverflow.com/questions/34856848/how-to-implement-the-unarchiver-delegate-for-overwriting-the-classname