我正在制作游戏中心游戏。我发送一个包含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
}
答案 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
}
}