Take the 2-minute tour ×

I am new to GKTurnBasedMatch and i'm trying to figure out what are good practices for the "matchData" sent between players during turns. All the tutorials i've found mainly cover sending a string of text and I would like to send a lot more than that. It would be great if someone could pint me to a more advanced tutorial.

An example of what I would like to do is a battle. The two players have their avatars and they have different details (health, attack, defence, etc), how should I send this data? The only way I see possible is to codify all the match details (a lot of them) into an NSDictionary and send that so that they can be put back into the custom match object again. Should I implement NSCoding?

Thank you!

share|improve this question
I think working with structs would be more efficient than NSDictionary instances. –  Kaan Dedeoglu Aug 24 '12 at 6:17
add comment

1 Answer

up vote 5 down vote accepted

I would implement a class that stores all the relevant information needed for a single turn and have the class implement NSCoding. This means you can convert an object to NSData on one player's device, then convert it back to an object on the other side.

This website http://samsoff.es/posts/archiving-objective-c-objects-with-nscoding has a simple example to get you going and here is an example of the main methods you need:

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {
        self.health = [decoder decodeObjectForKey:@"health"];
        self.attack = [decoder decodeObjectForKey:@"attack"];
        isDead = [decoder decodeBoolForKey:@"isDead"];
    return self;

- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:self.health forKey:@"health"];
    [encoder encodeObject:self.attack forKey:@"attack"];
    [encoder encodeBool:isDead forKey:@"isDead"];

Encoding your object to NSData:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject: object];

Converting back to an object:

id *object = [NSKeyedUnarchiver unarchiveObjectWithData: inputData];

The Archives and Serializations Programming Guide is also a great starting point.

Another option is using a library like RestKit and it's object mapping to/from JSON or XML.

share|improve this answer
Thank you very much! I appreciate that you took your time to make a custom example. –  gabriellanata Aug 24 '12 at 7:04
No problems. Send me a link to your game when you finish it, I'd love to try it out. –  danielbeard Aug 24 '12 at 7:33
The current NSData turn-based game size limit is 4096 bytes. Make sure to keep the data size low. An integer takes 4 bytes. In an array it piles up fast. I ended up to save everything in one string which reduced the data size tremendously. –  zeiteisen Aug 24 '12 at 7:44
Limit for turn-based games is now 64K developer.apple.com/library/ios/documentation/… –  conorgriffin Jan 9 at 0:04
add comment

Your Answer


