【问题标题】:Value conversion issue?价值转换问题?
【发布时间】:2014-10-10 15:31:09
【问题描述】:

由于某种原因,我不断收到“隐式转换失去整数精度”错误,它说它将它从 unsigned long 更改为 int(在我尝试随机化问题的部分中)。我对编程很陌生,我不知道如何解决这个问题。有人可以帮忙吗?

这是我的代码:

@interface ViewController ()
{
    NSArray *questionArray;
    UILabel *questionLabel;
}

@end

2) ViewDidLoad:

- (void)viewDidLoad
{
    [super viewDidLoad];
    //create question array
    questionArray = [NSArray arrayWithObjects:@"Question 1?", @"Question 2?", @"Question 3?", @"Question 4?", nil];

    //random a question
    int lowerBound = 0;
    int upperBound = [questionArray count] - 1;
    int randomValue = lowerBound + arc4random() % (upperBound - lowerBound);

    //create UILabel
    questionLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 20)];
    [questionLabel setTextAlignment:NSTextAlignmentCenter];
    [questionLabel setText:[questionArray objectAtIndex:randomValue]];
    [self.view addSubview:questionLabel];

    //create next button
    nextButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 150, 320, 100)];
    [nextButton setTitle:@"Next Question" forState:UIControlStateNormal];
    [nextButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [nextButton addTarget:self action:@selector(nextQuestionButtonSelected) forControlEvents:UIControlEventTouchUpInside];
}

【问题讨论】:

    标签: ios objective-c int implicit-conversion nsinteger


    【解决方案1】:

    您应该将这三行替换为:

    NSUInteger randomValue = arc4random_uniform((uint32_t) questionArray.count);
    

    这解决了您的代码中的几个问题。避免使用int。查看arc4random_uniform 的返回值并查看NSArray objectAtIndex: 的参数类型。都不返回int

    如果您为 64 位构建,这些类型变得更加关键。

    【讨论】:

    • 需要注意的是,arc4random_uniform 即使在 64 位平台上也总是返回一个uint32_t,所以如果有超过 4 个演出问题,方法将不起作用。在这种情况下不太可能,但可能是其他随机数生成实例的问题。我认为如果您不将 questionArray.count 转换为 uint32_t(为 64 位平台构建时),您仍然会收到相同的警告
    【解决方案2】:

    要解决该错误,您只需将结果转换为 int:

    int randomValue = (int)(lowerBound + arc4random() % (upperBound - lowerBound));
    

    但是,您更大的问题是,如果 [questionArray count] 为 1,您的代码将崩溃(除以 0),或者如果计数为 0,那么您将得到意想不到的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-12
      • 2014-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 1970-01-01
      • 2019-10-29
      相关资源
      最近更新 更多