Good practices for Game Center matchData

*爱你&永不变心* 提交于 2019-12-01 10:36:02

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.

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