NSKeyedUnarchiver unarchiveObjectWithData:data返回非nil对象,但具有nil属性 [英] NSKeyedUnarchiver unarchiveObjectWithData:data returns non nil object but with nil properties

查看:1038
本文介绍了NSKeyedUnarchiver unarchiveObjectWithData:data返回非nil对象,但具有nil属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立了一个包含一些模型类的快速框架,并且我在另一个ObjC应用程序中使用该框架没有任何问题.该应用程序使用NSKeyedArchiver/NSKeyedUnarchiverNSUserDefaults存储/检索数据对象:

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"];

其中,myCustomer是框架中的swift类的对象.要检索存储的对象,我要做:

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];

swift类如下:

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

问题在于,最近更新了swift框架(我对其他类(而不是Customer)进行了一些更改)后,从unarchiveObjectWithData中检索到的myCustomer的所有属性均为nil. 对象本身不是nil,但是其所有属性都是nil . myCustomer.email为nil,myCustomer.customerID为nil.当我切换回旧版本的框架时,上面的代码可以正常工作.

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.

过去几天一直在尝试各种方法,但没有任何效果.该应用程序的最低部署是iOS 12,该框架是使用swift 5.0编写的.真的很感谢任何提示,想法或答案.

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.

推荐答案

CodableNSCoding不同.要将Codable对象编码为plist文件,您需要使用PropertyListEncoder.如果您需要JSON数据,请使用JSONEncoder.要使您的对象符合NSCoding,可以检查此 post

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

这篇关于NSKeyedUnarchiver unarchiveObjectWithData:data返回非nil对象,但具有nil属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆