NSKeyedUnarchiver unarchiveObjectWithData:data ret

2020-05-03 10:56发布

问题:

I have built a swift framework that includes some model classes and I have been using the framework in another ObjC app without any problems. The app uses NSKeyedArchiver/NSKeyedUnarchiver to store/retrieve data objects from NSUserDefaults:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:myCustomer];
[self.prefs setObject:data forKey:@"mykey"];

where myCustomer is an object of a swift class from the framework. To retrieve the stored object I do:

NSData *data = [self.prefs dataForKey:@"mykey"];
Customer *myCustomer = [NSKeyedUnarchiver unarchiveObjectWithData:data];

The swift class looks like this:

@objc public class Customer: NSObject, Codable {
    @objc public var customerID: String
    @objc public var email: String?
}

The problem is that after updating the swift framework recently (I made some changes to some other classes not the Customer), myCustomer retrieved from unarchiveObjectWithData all its properties are nil. The object itself isn't nil but all its properties are nil. myCustomer.email is nil and myCustomer.customerID is nil. When I switch back to the old version of the framework, the code above works fine.

Have been trying various things for the past days and nothing has been working. Minimum deployment for the app is iOS 12 and the framework is written in swift 5.0. Would really appreciate any hints, ideas, or of course answers.

回答1:

Codable it is not the same as NSCoding. For encoding a Codable object into a plist file you need to use PropertyListEncoder. If you need JSON data just use JSONEncoder. To make your object NSCoding compliant you can check this post



回答2:

Just a assumption: does it help to declare the Swift vars dynamic? (See What does @objc dynamic var mean in Swift 4)