Good practices for Game Center matchData

前端 未结 1 847
天命终不由人
天命终不由人 2021-01-15 12:32

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 mai

相关标签:
1条回答
  • 2021-01-15 12:33

    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.

    0 讨论(0)
提交回复
热议问题