如何在Swift中将Int转换为NSData?

时间:2015-02-23 18:20:02

标签: ios swift int nsdata

在Objective-C中,我使用以下代码

  1. Int变量转换为NSData,即一个字节数据包。

    int myScore = 0;
    NSData *packet = [NSData dataWithBytes:&myScore length:sizeof(myScore)];
    
  2. 将转换后的NSData变量用于方法。

    [match sendDataToAllPlayers: 
    packet withDataMode: GKMatchSendDataUnreliable 
    error: &error];
    
  3. 我尝试将Objective-C代码转换为Swift:

    var myScore : Int = 0
    
    func sendDataToAllPlayers(packet: Int!,
                withDataMode mode: GKMatchSendDataMode,
                error: NSErrorPointer) -> Bool {
    
                return true
    }
    

    但是,我无法将Int变量转换为NSData并将其用作方法。我怎么能这样做?

7 个答案:

答案 0 :(得分:40)

使用Swift 3.x到5.0:

var myInt = 77
var myIntData = Data(bytes: &myInt, 
                     count: MemoryLayout.size(ofValue: myInt))

答案 1 :(得分:23)

Int转换为NSData

var score: Int = 1000
let data = NSData(bytes: &score, length: sizeof(Int))

var error: NSError?
if !match.sendDataToAllPlayers(data, withDataMode: .Unreliable, error: &error) {
    println("error sending data: \(error)")
}

将其转换回来:

func match(match: GKMatch!, didReceiveData data: NSData!, fromPlayer playerID: String!) {
    var score: Int = 0
    data.getBytes(&score, length: sizeof(Int))
}

答案 2 :(得分:3)

您可以这样转换:

var myScore: NSInteger = 0
let data = NSData(bytes: &myScore, length: sizeof(NSInteger))

答案 3 :(得分:1)

Swift 5 ,添加其他选项。

NSData很老,仍然有效

写入数据:

let buffer = NSMutableData()
let size = MemoryLayout<UInt>.size
let big = 1000
let small = 10
withUnsafeBytes(of: big, { (p) in
      let bufferPointer = p.bindMemory(to: UInt.self)
      if let address = bufferPointer.baseAddress{
             buffer.append(address, length: size)
      }
})

withUnsafeBytes(of: small, { (p) in
      let bufferPointer = p.bindMemory(to: UInt.self)
      if let address = bufferPointer.baseAddress{
           buffer.append(address, length: size)
      }
 })

读取数据:

if let d = buffer.copy() as? Data{
     var big: UInt = 0
     var small: UInt = 0
     let size = MemoryLayout<UInt>.size
     let meta = NSData(data: data)
     meta.getBytes(&big, range: NSRange(location: 0, length: size))
     meta.getBytes(&small, range: NSRange(location: size, length: size))

     print("big:", big, "\nsmall:", small)
    //  big: 1000 
    //  small: 10 
}

您知道内存布局,数据已放入内存中,

然后将它们准确地放出来。

unsafe方法很有趣

答案 4 :(得分:0)

使用此初始值设定项将每个数组转换为数据

Data(element: Sequence)

示例:

let myArr     = [12,45,67,898, 100]
let myArrData = Data(myArr)

答案 5 :(得分:0)

对于任何整数类型:

extension FixedWidthInteger {
    var data: Data {
        let data = withUnsafeBytes(of: self) { Data($0) }
        return data
    }
}

示例:

let data = 1.data

答案 6 :(得分:-1)

根据要使用的Int的大小,一种直接的方法是使用UInt8的序列初始化数据:

let value: Int = 100
let data = Data([UInt8(value)])
// OR
let data = Data([0xFF, 0xFE])