隐式转换失去整数精度' NSUInteger' (又名' unsigned long')to' int'制作应用程序时?

时间:2014-04-09 02:40:07

标签: ios objective-c

我正在编码,然后碰到了这个......

我不明白为什么会这样,我需要帮助,有人可以帮忙吗? :)

- (void)viewDidLoad
{
Start = YES;
Obstacle.hidden = YES;
Obstacle2.hidden = YES;
Bottom1.hidden = YES;
Bottom2.hidden = YES;
Bottom3.hidden = YES;
Bottom4.hidden = YES;
Bottom5.hidden = YES;
Bottom6.hidden = YES;
Bottom7.hidden = YES;
Top1.hidden = YES;
Top2.hidden = YES;
Top3.hidden = YES;
Top4.hidden = YES;
Top5.hidden = YES;
Top6.hidden = YES;
Top7.hidden = YES;

Heli.center = CGPointMake(48, 145);

HighScore = [[NSUserDefaults standardUserDefaults] integerForKey:@"HighScoreSaved"]; < issue HERE

Intro3.text = [NSString stringWithFormat:@"High Score: %i", HighScore];

3 个答案:

答案 0 :(得分:5)

integerForKey返回NSUInteger值(也称为unsigned long)。我假设你的HighScore变量是一个int,它的字节数比long长。尝试转换为int:

HighScore = (int)[[NSUserDefaults standardUserDefaults] integerForKey:@"HighScoreSaved"];

答案 1 :(得分:0)

我猜这是你的倒数第二行。 integerForKey:返回NSUInteger(unsigned long),HighScore可能被声明为int(您不在代码中显示声明)。使用(int)显式转换它,或者将其作为int存储在用户默认值(intForKey:)中。祝你好运!

答案 2 :(得分:0)

如果您包含HighScore的声明会很好,但我会假设它是int,因为这是您遇到问题的类型。当您将HighScore分配给-[NSUserDefaults integerForKey:]的结果时,您要将NSUInteger类型的变量分配到int类型。这是你问题的根源。由于NSUIntegerunsigned long的类型定义而long是数字的更大表示而不是int,因此在分配期间,您将失去精确度。我有两个推荐。

@property (nonatomic) NSUInteger HighScore; // declare HighScore as NSUInteger

/* or */

HighScore = (int)[[NSUserDefaults standardUserDefaults] integerForKey:@"HighScoreSaved"];

第一个简单地将HighScore声明为NSUInteger以首先避免该问题,第二个将该方法的返回类型转换为适合其赋值。