Swift结构到NSData并返回

前端之家收集整理的这篇文章主要介绍了Swift结构到NSData并返回前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个包含一个struct和一个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)

如何最好地将该Patch序列化为NSData,如何最佳地将其排序?

运用

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

只给我一个名字和数据的指针.我正在探索NSKeyedArchiver,但是我必须使Packet成为一个对象,我更希望保留一个结构体.

干杯

没有得到任何反馈,这是我结束的解决方案:

>为我的结构生成encode()和decode()函数
>将Int更改为Int64,因此Int在32位和64位平台上具有相同的大小
有一个没有String或Data的中间结构(ArchivedPacket),只有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
    }
}

猜你在找的Swift相关文章