如何以随机顺序显示问题?

时间:2015-10-24 03:45:47

标签: ios objective-c nsarray

我使用Obj.C进行了测验。我想要做的是让问题以随机顺序出现。我尝试了很多方法,但到目前为止我都失败了。

+ (NSArray *) myArray
{
    static NSArray *theArray;
    if (!theArray)
    {
        theArray = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:0], nil];
    }
    return theArray;
}

+ (NSArray *) questions {
    return @[
             @{@"question":

1 个答案:

答案 0 :(得分:0)

这是我如何从另一个数组生成随机数组。

NSArray *myArray = @[object1, object2, object3, ..., objectN];
NSMutableArray *arrayToTakeItemsFrom = [[NSMutableArray alloc] arrayWithArray:myArray];
NSMutableArray *randomOrderedArray = [NSMutableArray new];

while (arrayToTakeItemsFrom.count > 0) {
    int randomIndex = arc4random_uniform(arrayToTakeItemsFrom.count);
    MyObjectClass *swapObject = [arrayToTakeItemsFrom objectAtIndex:randomIndex];
    [arrayToTakeItemsFrom removeObject:swapObject];
    [randomOrderedArray addObject:swapObject];
}

//Now randomOrderedArray has everything myArray has in it but in a random order, and always works for any size array including an empty array