将NSString转换为Int - Game Center

时间:2012-01-26 20:37:22

标签: iphone nsstring int game-center gamekit

我正在开发一个使用游戏中心的应用程序,但我遇到了问题。我希望玩家将他们的分数提交给排行榜,这样他们就可以挑战朋友。这是NSString分数的代码。

-(IBAction)gasPedalPressed:(id)sender {

double noSeconds = (double) [self.startDate timeIntervalSinceNow] * -1000;


NSString *reactionTime= [[NSString alloc] initWithFormat:@"Good Job! You're reaction time is %1.0f Ms. Let's see if you can do better...", noSeconds];

NSString *time= [[NSString alloc] initWithFormat:@"%1.0f Ms", noSeconds];


if(greenLightOn == 0)
    reactionTime = @"Slow down! You have to wait for the green light. Let's see if you can do better...";

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Reaction Time" message:reactionTime 
                                               delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];

这就是我想要遵守的:

-(IBAction)submitscore:(id)sender {
GKScore *scoreReporter = [[GKScore alloc] initWithCategory:@"1234567890"];

scoreReporter.value = score.text;    
[scoreReporter reportScoreWithCompletionHandler:^(NSError *error) {



    if (error !=nil) {;
        NSLog(@"failed sub score");
    } else {

        NSLog(@"submitted score");

    }
}


 ];

}

请帮助!!

1 个答案:

答案 0 :(得分:2)

如果您有字符串:

NSSting *myString = [NSString stringWithString:@"2"];

您可以使用以下字符从字符串中获取int值:

int i = [myString intValue];

[edit] - 回复你的评论:

由于您已经创建了noSeconds作为double,因此实际上不需要将其转换为NSString然后再返回。您只需将noSeconds传递给您创建的GKScore实例即可。

为了让您的'submitScore'方法了解您的变量'noSeconds',您需要将其创建为实例变量。 (或者你可以将它作为方法参数传递)

所以,在你的.h:

double noSeconds;

@property (nonatomic, assign) double noSeconds;

然后在你的.m:

@synthesize noSeconds;

-(IBAction)gasPedalPressed:(id)sender {
    ...
    noSeconds = (double) [self.startDate timeIntervalSinceNow] * -1000;
    ...
}

-(IBAction)submitscore:(id)sender {
    ...
    GKScore *scoreReporter = [[[GKScore alloc] initWithCategory:@"123"] autorelease];
    scoreReporter.value = noSeconds;
    ...
}

查看适用的文档总是有帮助的:GKScore Docs