2011-07-25 41 views
0

現在我正在根據可以正常工作的圖像名稱設置一個隊列。它通過圖像0到13循環並將它們添加到隊列中。在Obj-C中隨機填充隊列

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,則是多餘且效率低下的。

回答

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

其實我不是。 'iOS中的ARC' 5.像一個魅力工作;) –

+1

這更好。雖然我不知道ARC的詳細信息:-) – taskinoor

+0

http://clang.llvm.org/docs/AutomaticReferenceCounting.html –

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. 
}