将本地播放器的别名(或任何文本)发送到另一台设备的最佳方法是什么,因为我不能因为ARC /指针而在我的结构中放置NSString?
到目前为止,我已尝试转换为&从char数组中,使用__unsafe_unretained-选项并尝试创建一个类来放入文本。尽管这三个尝试都是通过编译完成的,但它们会使设备崩溃(模拟器继续运行但不显示别名。)
使用ARC时,在多人游戏中发送文字真的很困难吗?我面临的问题很可能是因为我对编程不是很有经验......所以如果有人能指出我正确的方向或者给我提供一些代码,我真的很感激
答案 0 :(得分:1)
您可以轻松地将字符串编码和解码为NSData对象,并通过Game Center发送。
要编码:在字符串上使用此方法
- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding
使用编码:NSUTF8StringEncoding
这将返回一个NSData对象
解码;
NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
编辑:
基本上你永远不必明确地发送玩家别名。有两种情况:
1:GKTurnBasedMatch
如果你正在使用它,那么这里是如何获得所有别名(包括你的)的列表
NSMutableArray *playerIds = [NSMutableArray arrayWithCapacity:match.participants.count];
for (GKTurnBasedParticipant *part in match.participants) {
if([participant.playerID isKindOfClass:[NSString class]]){
[playerIds addObject:part.playerID];
}
} //at this point you have an array full of playerID strings, next you call this:
[GKPlayer loadPlayersForIdentifiers:(NSArray *)playerIds withCompletionHandler:(void (^) (NSArray *players, NSError *error))completionHandler {
for (GKPlayer *playa in players) {
NSLog(@"%@",playa.alias); // here i'm just logging the aliases but you can do whatever..
}
}];
2.GKMatch:这个案例要容易得多,因为你的GKMatch已经有了playerIDs数组,与以前一样:
[GKPlayer loadPlayersForIdentifiers:(NSArray *) match.playerIDs withCompletionHandler:(void (^)(NSArray *players, NSError *error))completionHandler {
//again you get the array players full of GKPlayer objects , simply pull the alias you want
}];