我會實現一個類,它存儲單個回合所需的所有相關信息,並讓類實現NSCoding。這意味着您可以在一個玩家的設備上將對象轉換爲NSData,然後將其轉換回另一側的對象。
本網站http://samsoff.es/posts/archiving-objective-c-objects-with-nscoding有一個簡單的例子,讓你去和這裏的主要方法的一個例子,你需要:
- (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"];
}
編碼的對象的NSData:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject: object];
轉換回一個對象:
id *object = [NSKeyedUnarchiver unarchiveObjectWithData: inputData];
The Archives and Serializations Programming Guide is als o一個很好的起點。
另一種選擇是使用像RestKit這樣的庫,它是從JSON或XML映射到/從JSON或XML。
我認爲使用結構會比NSDictionary實例更高效。 –