我正在制作Game Center游戏。我发送一个包含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

}

最佳答案

假设您的意思是“从 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
    }
}

关于ios - 在Swift中从NSData中提取结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26305359/

10-09 12:48