Reading random values from an array

前端 未结 5 1283
长情又很酷
长情又很酷 2021-01-18 11:39

I have an array with a 14 strings. I want to display each of these 14 strings to the user without duplicates. The closest I got was creating an array of integers and shuffli

5条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-18 12:15

    This task is very easy using an NSMutableArray. In order to do this, simply remove a random element from the array, display it to the user.

    Declare a mutable array as an instance variable

    NSMutableArray * questions;
    

    When the app launches, populate with values from myArray

    questions = [[NSMutableArray alloc] initWithArray:myArray]];
    

    Then, to get a random element from the array and remove it, do this:

    int randomIndex = (arc4random() % [questions count]);
    NSDictionary * anObj = [[[questions objectAtIndex:randomIndex] retain] autorelease];
    [questions removeObjectAtIndex:randomIndex];
    // do something with element
    hintText.text = [anObj objectForKey:@"hint"];
    questionText.text = [anObj objectForKey:@"question"];
    

提交回复
热议问题