我如何发送一个名为 Deck *deck 的核心数据对象,它包含一个 NSString、一个 NSData 照片对象和一个 NSSet(与其他实体的一对多关系)。
当我尝试使用 [GKMatch sendData:toPlayers:] 方法发送 Deck *deck 时,根据调试控制台,NSData *outgoingPacket 仍然为零,但 *deck 有一个地址。
- (void) sendDeck {
NSError *error;
NSData *outgoingPacket = [NSData dataWithBytes:&_deck length:sizeof(_deck)];
[self.myMatch sendData:outgoingPacket toPlayers:[NSArray arrayWithObject:self.pickerViewFriend] withDataMode:GKMatchSendDataReliable error:&error];
//myMatch is an instance of GKMatch.
//_deck is an instance variable set by @property Deck *deck, which is assigned by a UIPickerView, which works perfectly
}
(我意识到这甚至没有解决发送与牌组相关的卡片的问题,但我被困在了这一点上)
最佳答案
这条线有几个问题:
NSData *outgoingPacket = [NSData dataWithBytes:&_deck length:sizeof(_deck)];
因为
_deck
是一个指向对象(Deck
的实例)的指针,sizeof(_deck)
只是给你指针的大小。这对于单个内存地址来说已经足够大了。您无法真正修复调用,因为
dataWithBytes:length:
使用连续的内存块。您的托管对象极不可能通过该测试。
您可以单独发送每个字段,但这有点困惑。一个更简单的替代方法是使用 NSDictionary
作为您的传输对象。根据需要在NSDictionary
和Deck
之间进行转换,并将NSDictionary
编码为NSData
进行传输。像这样的东西:
NSDictionary *dict = // Fill this with the values you want to send
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dict];
然后在另一端,
NSData *data = // data received from other device
NSDictionary *dict = [NSKeyedUnarchiver unarchiveObjectWithData:data];
关于ios - 将 CoreData NSManagedObject 发送给 Game Center 中的另一个玩家,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20406229/