美文网首页
swift struct如何归档解档

swift struct如何归档解档

作者: MrStock | 来源:发表于2023-05-10 23:03 被阅读0次

struct不能被序列化成NSData,不能归解档,class可以,因为归解档的类必须遵守 NSCoding协议,而NSCoding只适用于继承自NSObject的类,struct不能遵守NSCoding协议。(上述摘录)

解决方案:

定义一个protocol,包含两个方法:

1.从结构体中得到一个NSDictionary对象

2.使用一个NSDictionary对象实例化结构体 NSDictionary可以使用NSKeyedArchiver进行序列化 好处:所有遵守该协议的结构体都可以被序列化(上述摘录)

感觉挺麻烦,我做了个简单的实验。可以正常转换。。

要归档的struct转成NSData呗,解档了再转成struct。貌似更简单点,欢迎指导

NSData遵守NSSecureCoding协议,NSSecureCoding协议继承自NSCoding。struct TestStruct {

            var age:Int

        }

        var date =TestStruct(age:36)

        var msg: NSData = NSData(bytes: &date, length: MemoryLayout<TestStruct>.stride(ofValue: date));

        print(msg);

        var unMsg:TestStruct = TestStruct(age: 10)

        msg.getBytes(&unMsg, length: MemoryLayout<TestStruct>.stride(ofValue: date))

        print(msg, unMsg)

相关文章

网友评论

      本文标题:swift struct如何归档解档

      本文链接:https://www.haomeiwen.com/subject/msnjsdtx.html