价值转换问题?

时间:2014-08-17 16:17:33

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

出于某种原因,我不断得到"隐式转换失去整数精度"错误,它说它从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];
}

2 个答案:

答案 0 :(得分:1)

您应该用以下内容替换这三行:

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

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

如果构建为64位,则这些类型会变得更加重要。

答案 1 :(得分:0)

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

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

然而,更大的问题是,如果[questionArray count]为1,您的代码将崩溃(除以0)或如果计数为0则会出现意外结果。