Game Development Reference
This code first casts the received data bytes to a pointer to an SBasePacket
struct. Notice in Listing 14-25 that that's the struct that contains only the type field.
Because you've declared that all packets must have this field at its first entry, any pack-
et can be safely cast to SBasePacket . The switch statement inspects the type, and
depending on the network packet, further processing is done—but not without casting
the packet to the actual packet type. For example, if the basePacket-> type is
kPacketTypeScore , the basePacket is cast to an SScorePacket to allow the
code to access the score field.
Tip When checking packets, it's a good idea to add the default option.
You'll frequently add new packets, and from time to time you'll forget to
handle this particular packet type on the receiving end. So, logging this as an
error or even throwing an exception is recommended. Otherwise, you may see
bugs in your app that could be hard to track down.
Actually sending the packets is relatively easy and follows the same principle. You first
create a new variable with one of the packet structs as its data type. Then you fill in
each field of the struct and pass it to the GameKitHelper method
memory because Game Kit makes a copy of the struct and thus takes over the memory
management of the packet. Because sendDataToAllPlayers required a pointer,
the packet is prefixed with the reference operator (ampersand character) &packet
to denote that the packet variable's address is passed instead of the packet itself.
// send a bogus score (simply an integer increased every time it is sent)
if ([GameKitHelper sharedGameKitHelper].currentMatch != nil)