1

我一直在研究这个问题一段时间,但找不到有效的解决方案。我正在创建一个游戏,其中每个玩家都被分配了一个随机名称。在游戏结束时,如果一个或多个玩家的分数使他们有资格进入历史排行榜,我想遍历所有玩家,显示一个 UIAlertView,他们可以在其中输入他们的真实姓名,然后将该姓名保存回我的玩家对象。但是,我无法让循​​环停止、显示警报视图、等待响应,然后继续。有人可以帮帮我吗?

这是我的循环:

for (int i = 0; i < [leaderboard count]; i++) {
    NSDictionary *player = [[NSDictionary alloc] initWithDictionary:[leaderboard objectAtIndex:i]];
    if ([[player valueForKey:@"isCurrentPlayer"] isEqualToString:@"YES"]){
        // getRealPlayerName takes in a name parameter and displays an alertview
        [self performSelectorOnMainThread:@selector(getRealPlayerName:) withObject:[player valueForKey:@"playerName"] waitUntilDone:YES];
        // nameFromAlertView is a local variable that is set when the user enters a name in the alertview.
        [player setValue:[self nameFromAlertView] forKey:@"playerName"];
        [player setValue:@"" forKey:@"isCurrentPlayer"];
    }
}
4

2 回答 2

2

你不能循环执行。

而是将用户和点保存在数组中,调用显示 UIAlertView 的方法。从数组中获取第一个用户信息并从数组中删除这些信息。设置警报视图的委托。一旦输入了第一个信息,就会调用 UIAlertView 的委托方法(alertView:didDismissWithButtonIndex:)。你处理输入的信息,然后检查数组中是否还有东西,如果有,再次调用第一个方法


-(void)promptForInput
{
    self.currentUserInfo = userArray[0]; //userarray is mutable, self.currentUserInfo is a property for the current user
    [userArray removeObject:self.currentUserInfo];
    //configure UIAlertView
    alertView.delegate = self;

}


//once the user hit a altertview button, this delegate method gets called
-(void)alertView:(UIAlertView)alertView didDismissWithButtonIndex:(NSUInteger)idx
{
     //save/process entered data, self.currentUserInfo hold the current user.

    if([userArray count]> 0){
        [self promptForInput];
    }
}

如果您熟悉块,您还可以使用第三方代码,它允许使用块而不是委托。但是在块中你会做基本相同的事情:只要数组中的用户未被处理,就调用另一个块。

新增内容之一:Mugunth Kumar — 基于块的 UIAlertView 和 UIActionSheet

于 2013-03-24T18:06:54.710 回答
1

只有当程序控制返回到主运行循环时,才会显示警报视图并处理事件。因此在等待

[self performSelectorOnMainThread:@selector(getRealPlayerName:) withObject:[player valueForKey:@"playerName"] waitUntilDone:YES];

完全阻止显示警报视图。

你可以做的是:

  • 为第一个玩家启动警报视图。
  • alertView:didDismissWithButtonIndex:委托函数中,记录数据并为下一个玩家(如果不是最后一个玩家)启动一个新的警报视图。

您必须将当前玩家索引存储在类的属性中。或者,您可以将当前索引分配给myAlertView.tag.

于 2013-03-24T18:06:11.537 回答