Matt
Matt

Reputation: 57

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

Upvotes: 0

Views: 180

Answers (2)

rmaddy
rmaddy

Reputation: 318804

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.

Upvotes: 1

Joel
Joel

Reputation: 16124

To resolve that error you can simply cast the result to an int:

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

However, your bigger problem is that if [questionArray count] is 1 your code will crash (division by 0) or if the count is 0 then you will get an unexpected result.

Upvotes: 0

Related Questions