现在我正在建立一个基于图像名称的队列,工作正常。它循环遍历图像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
,这是多余且低效的。
答案 0 :(得分: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
。
答案 1 :(得分: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.
}