Search code examples
objective-cnsstringnsoperationqueuearc4random

Populating Queue Randomly in Obj-C


Right now I am setting up a queue based off of image names that works fine. It loops through images 0 through 13 and adds them to the queue.

loadImagesOperationQueue = [[NSOperationQueue alloc] init];

NSString *imageName;
for (int i=0; i < 13; i++) {
    imageName = [[NSString alloc] initWithFormat:@"cover_%d.jpg", i];
    [(AFOpenFlowView *)self.view setImage:[UIImage imageNamed:imageName] forIndex:i];
    NSLog(@"%d is the index",i);

}

This works flawlessly; the queue is set up from cover_0.jpg through cover_13.jpg. I want to add a little randomness to it, however. If I just use an arc4random() I will undoubtedly get the same image added to the queue multiple times. Logically, how can I get arc4random() to be exclusive. Adding the chosen numbers to a string and then checking them against the current output, and if needed repeating the arc4, is redundant and inefficient.


Solution

  • Do something like this.

    NSMutableArray *tmpArray = [[NSMutableArray alloc] initWithCapacity:14];
    
    for (int i = 0; i < 13; i++) {
        [tmpArray addObject:[NSString stringWithFormat:@"cover_%d.jpg", i]];
    }
    
    for (int i = 0; i < 13; i++) {
        int index = arc4random() % [tmpArray count];
        NSString *imageName = [tmpArray objectAtIndex:index];
        [tmpArray removeObjectAtIndex:index];
        [(AFOpenFlowView *)self.view setImage:[UIImage imageNamed:imageName] forIndex:i];
    }
    
    [tmpArray release];
    

    And your code should not work flawlessly. You are leaking imageName.