Cannot decode object of class Employee for key (NS.object.0); the class may be defined in source code or a library that is not linked

喜欢而已 提交于 2019-12-05 14:01:54

问题


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 serializing
  • NSKeyedUnarchiver.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 DemoNote from the app to a framework did change the module name, which meant that NSKeyedUnarchiver couldn'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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!