小编典典

Swift结构到NSData并返回

swift

我有一个包含一个结构的结构,NSObject并且我想序列化为一个NSData对象:

struct Packet {
  var name: String
  var index: Int
  var numberOfPackets: Int
  var data: NSData
}

var thePacket = Packet(name: name, index: i, numberOfPackets: numberOfPackets, data: packetData)

如何最好地将Packet序列化为NSData,以及如何最好地对其进行反序列化?

使用

var bufferData = NSData(bytes: & thePacket, length: sizeof(Packet))

只给了我名称和数据的指针。我正在探索NSKeyedArchiver,但是随后我必须将Packet作为对象,并且我希望将其保留为结构。

干杯

尼克


阅读 354

收藏
2020-07-07

共1个答案

小编典典

没有真正得到任何反馈,这是我最终得到的解决方案:

  1. 我的结构的制造encode()decode()功能
  2. 更改Int为,Int64以便Int在32位和64位平台上具有相同的大小
  3. 具有一个中间结构(ArchivedPacket),该结构没有String或Data,而只有Int64

这是我的代码,非常感谢您的反馈,尤其是在没有那么麻烦的方法的情况下:

public struct Packet {
    var name: String
    var index: Int64
    var numberOfPackets: Int64
    var data: NSData

    struct ArchivedPacket {
        var index : Int64
        var numberOfPackets : Int64
        var nameLength : Int64
        var dataLength : Int64
    }

    func archive() -> NSData {

        var archivedPacket = ArchivedPacket(index: Int64(self.index), numberOfPackets: Int64(self.numberOfPackets), nameLength: Int64(self.name.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)), dataLength: Int64(self.data.length))

        var metadata = NSData(
            bytes: &archivedPacket,
            length: sizeof(ArchivedPacket)
        )

        let archivedData = NSMutableData(data: metadata)
        archivedData.appendData(name.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!)
        archivedData.appendData(data)

        return archivedData
    }

    func unarchive(data: NSData!) -> Packet {
        var archivedPacket = ArchivedPacket(index: 0, numberOfPackets: 0, nameLength: 0, dataLength: 0)
        let archivedStructLength = sizeof(ArchivedPacket)

        let archivedData = data.subdataWithRange(NSMakeRange(0, archivedStructLength))
        archivedData.getBytes(&archivedPacket)

        let nameRange = NSMakeRange(archivedStructLength, Int(archivedPacket.nameLength))
        let dataRange = NSMakeRange(archivedStructLength + Int(archivedPacket.nameLength), Int(archivedPacket.dataLength))

        let nameData = data.subdataWithRange(nameRange)
        let name = NSString(data: nameData, encoding: NSUTF8StringEncoding) as! String
        let theData = data.subdataWithRange(dataRange)

        let packet = Packet(name: name, index: archivedPacket.index, numberOfPackets: archivedPacket.numberOfPackets, data: theData)

        return packet
    }
}
2020-07-07