Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 786
user2189878 Avatar asked May 04 '16 12:05

user2189878


2 Answers

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.

like image 73
teriiehina Avatar answered Oct 20 '22 13:10

teriiehina


For me it was happening in my Today extension. What fixed it was adding @objc(MyExampleClass) before the declaration.

@objc(MyExampleClass)
open class MyExampleClass {
....
}
like image 37
Stefan S Avatar answered Oct 20 '22 13:10

Stefan S