从NSData的斯威夫特提取结构(Extract struct from NSData in Swi

2019-10-21 03:33发布

我在做游戏中心的游戏。 我发送包含一个数据包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

}

Answer 1:

假设你的意思是“它解码来自背部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
    }
}


文章来源: Extract struct from NSData in Swift