Swift结构到NSData并返回

前端之家收集整理的这篇文章主要介绍了Swift结构到NSData并返回前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个包含一个struct和一个NSObject的结构体,我想序列化成一个NSData对象:
  1. struct Packet {
  2. var name: String
  3. var index: Int
  4. var numberOfPackets: Int
  5. var data: NSData
  6. }
  7.  
  8. var thePacket = Packet(name: name,index: i,numberOfPackets: numberOfPackets,data: packetData)

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

运用

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

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

干杯

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

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

这是我的代码,我将非常感谢您的反馈,特别是如果有更少的麻烦的方式来做到这一点:

  1. public struct Packet {
  2. var name: String
  3. var index: Int64
  4. var numberOfPackets: Int64
  5. var data: NSData
  6.  
  7. struct ArchivedPacket {
  8. var index : Int64
  9. var numberOfPackets : Int64
  10. var nameLength : Int64
  11. var dataLength : Int64
  12. }
  13.  
  14. func archive() -> NSData {
  15.  
  16. var archivedPacket = ArchivedPacket(index: Int64(self.index),numberOfPackets: Int64(self.numberOfPackets),nameLength: Int64(self.name.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)),dataLength: Int64(self.data.length))
  17.  
  18. var Metadata = NSData(
  19. bytes: &archivedPacket,length: sizeof(ArchivedPacket)
  20. )
  21.  
  22. let archivedData = NSMutableData(data: Metadata)
  23. archivedData.appendData(name.dataUsingEncoding(NSUTF8StringEncoding,allowLossyConversion: false)!)
  24. archivedData.appendData(data)
  25.  
  26. return archivedData
  27. }
  28.  
  29. func unarchive(data: NSData!) -> Packet {
  30. var archivedPacket = ArchivedPacket(index: 0,numberOfPackets: 0,nameLength: 0,dataLength: 0)
  31. let archivedStructLength = sizeof(ArchivedPacket)
  32.  
  33. let archivedData = data.subdataWithRange(NSMakeRange(0,archivedStructLength))
  34. archivedData.getBytes(&archivedPacket)
  35.  
  36. let nameRange = NSMakeRange(archivedStructLength,Int(archivedPacket.nameLength))
  37. let dataRange = NSMakeRange(archivedStructLength + Int(archivedPacket.nameLength),Int(archivedPacket.dataLength))
  38.  
  39. let nameData = data.subdataWithRange(nameRange)
  40. let name = NSString(data: nameData,encoding: NSUTF8StringEncoding) as! String
  41. let theData = data.subdataWithRange(dataRange)
  42.  
  43. let packet = Packet(name: name,index: archivedPacket.index,numberOfPackets: archivedPacket.numberOfPackets,data: theData)
  44.  
  45. return packet
  46. }
  47. }

猜你在找的Swift相关文章