从Swift中的NSData中提取struct

时间:2014-10-10 17:58:53

标签: ios pointers struct swift nsdata

我正在制作游戏中心游戏。我发送一个包含struct MovePacket的数据包,如下所示:

var packet = MovePacket(packetID: 1, move: myMove)

let dataPacket = NSData(bytes: &packet, length: sizeof(MovePacket))

currentMatch!.sendDataToAllPlayers(dataPacket, withDataMode: GKMatchSendDataMode.Reliable, error: nil)

这与Objective-C类似,但我不了解如何将收到的NSData解码回我的struct MovePacket。这是我的尝试之一:

func match(match: GKMatch!, didReceiveData data: NSData!, fromRemotePlayer player: GKPlayer!) {

    var packet : MovePacket 

    data.getBytes(&packet, length: sizeof(MovePacket)) // getting error here: Address of variable 'packet' taken before it is initialized

    println(packet) //Variable 'packet' used before being initialized

}

1 个答案:

答案 0 :(得分:4)

假设您的意思是“从 NSData ”解码回来:

func match(match: GKMatch!, didReceiveData data: NSData!, fromRemotePlayer player: GKPlayer!) {
    if data.length == sizeof(MovePacket) {
        let packet = UnsafePointer<MovePacket>(data.bytes).memory
        println(packet)
    } else {
        // error: data size is incorrect
    }
}