0

现在我正在根据工作正常的图像名称设置一个队列。它遍历图像 0 到 13 并将它们添加到队列中。

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);

}

这完美无缺;队列是从cover_0.jpg 到cover_13.jpg 设置的。不过,我想给它添加一点随机性。如果我只使用一个,arc4random()我无疑会多次将相同的图像添加到队列中。从逻辑上讲,我怎样才能arc4random()成为排他性的。将所选数字添加到字符串中,然后根据当前输出检查它们,如果需要重复arc4, 是多余且低效的。

4

2 回答 2

1

做这样的事情。

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

而且您的代码不应完美运行。你在泄漏imageName

于 2011-07-25T16:16:45.213 回答
0

我会先用图像名称填充一个数组,然后随机选择值:

NSMutableArray * imageNames = [NSMutableArray array];
for (int i = 0; i < 13; i++) {
    NSString * iName = [NSString stringWithFormat:@"cover_%d.jpg", i];
    [imageNames addObject:iName];
}
while ([imageNames count] > 0) {
    int index = arc4random() % [imageNames count];
    NSString * iName = [imageNames objectAtIndex:index];
    [imageNames removeObjectAtIndex:index];
    // load image named iName here.
}
于 2011-07-25T16:15:19.447 回答