Extract struct from NSData in Swift

北城以北 提交于 2019-12-11 10:51:53

问题


I'm making Game Center game. I send a data packet containing a struct MovePacket like this:

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

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

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

This works like in Objective-C, but I don't understand how to decode the received NSData back to my struct MovePacket. This is one of my tries:

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:


Assuming you meant “decode it back from 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
    }
}


来源:https://stackoverflow.com/questions/26305359/extract-struct-from-nsdata-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!