Search code examples
iosobjective-cintimplicit-conversionnsinteger

Value conversion issue?


For some reason I keep getting the "implicit conversion loses integer precision" error and it says it changes it from unsigned long to int (in the section where I am trying to randomize the question). I am very new to programming and I don't know how I can fix this problem. Can anyone please help?

Here is my code:

@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];
}

Solution

  • You should replace the three lines with:

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

    This solves several issues in your code. Avoid using int. Look at the return value of arc4random_uniform and look at the parameter type for NSArray objectAtIndex:. Neither return int.

    If you build for 64-bit, these types become more critical.