Good practices for Game Center matchData

2019-02-19 19:24发布

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!

1条回答
孤傲高冷的网名
2楼-- · 2019-02-19 19:49

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.

查看更多
登录 后发表回答