问题
Im trying to pass an array of 'Employee' objects iPhone to Apple Watch by serializing the array :
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:employees];
and unserializing it as on the Watch side:
NSMutableArray *employees = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
This is the 'Employee' class:
@interface Employee : NSManagedObject
@property (nonatomic, retain) NSNumber * employeeID;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSNumber * age;
@property (nonatomic, retain) NSString * address;
@property (nonatomic, retain) NSString * designation;
@property (nonatomic, retain) NSString * teamName;
@property (nonatomic, retain) NSString * gender;
@property (nonatomic, retain) NSNumber * dateOfJoining;
@end
Do I have to do any changes on the Watch side to fix this error?
回答1:
so I just had that exact same problem and the answer is simple but a little hard to find by oneself.
You simply have to use:
NSKeyedArchiver.setClassName("Employee", for: Employee.self)
before serializingNSKeyedUnarchiver.setClass(Employee.self, forClassName: "Employee")
before deserializing
wherever needed.
Looks like iOS extensions prefix the class name with the extension's name.
回答2:
For me it was happening in my Today extension. What fixed it was adding @objc(MyExampleClass) before the declaration.
@objc(MyExampleClass)
open class MyExampleClass {
....
}
回答3:
teriiehina's answer got me part of the way there; I could archive and unarchive to clean devices but still got the above error when trying to unarchive an existing archive.
Eventually I found this question: Added a custom framework, now Swift can't unarchive data, which the user answered himself:
Moving
DemoNotefrom the app to a framework did change the module name, which meant thatNSKeyedUnarchivercouldn't find instances of the archived class due to a name mismatch.
His solution of prefixing the old project's name to the className string (e.g. if the project was called "CompanyDirectory" then using "CompanyDirectory.Employee" as opposed to just "Employee") was what I needed to be able to unarchive my data from my model which had been moved into a newly-created linked Framework.
来源:https://stackoverflow.com/questions/37028194/cannot-decode-object-of-class-employee-for-key-ns-object-0-the-class-may-be-d