2011-10-29 75 views
2

我有一個NSArray,它包含索引0-9中的10個對象。數組中的每個條目都是一個引號。從NSArray中選擇一個隨機對象索引

當我的用戶選擇「隨機引用」選項時,我希望能夠從數組中選擇一個隨機條目並顯示該條目中包含的文本。

任何人都可以指出我如何實現這一目標的正確方向?

+0

可能重複(http://stackoverflow.com/questions/3318902/picking-a-random-object-in-an-nsarray) –

回答

6

我建議你用這個代替硬編碼的10;這樣,如果添加更多引用,它會自動解決,而不需要更改該編號。 [在一個NSArray採摘隨機對象]的

NSInteger randomIndex = arc4random()%[array count]; 
NSString *quote = [array objectAtIndex:randomIndex]; 
+0

完美,這是一個很好的想法來數組。謝謝。 –

+0

太棒了!非常感謝! – Farini

0

首先,在你的界限之間得到一個隨機數,參見this discussion和相關的手冊頁。然後用它索引到數組中。

int random_number = rand()%10; // Or whatever other method. 
return [quote_array objectAtIndex:random_number]; 

編輯:對於那些誰也不能正確地從鏈接插值或只是不小心閱讀提示參考,讓我清楚這一點對你:

// Somewhere it'll be included when necessary, 
// probably the header for whatever uses it most. 
#ifdef DEBUG 
#define RAND(N) (rand()%N) 
#else 
#define RAND(N) (arc4random()%N) 
#endif 

... 

// Somewhere it'll be called before RAND(), 
// either appDidLaunch:... in your application delegate 
// or the init method of whatever needs it. 
#ifdef DEBUG 
// Use the same seed for debugging 
// or you can get errors you have a hard time reproducing. 
srand(42); 
#else 
// Don't seed arc4random() 
#endif 

.... 

// Wherever you need this. 
NSString *getRandomString(NSArray *array) { 
    #ifdef DEBUG 
    // I highly suggest this, 
    // but if you don't want to put it in you don't have to. 
    assert(array != nil); 
    #endif 
    int index = RAND([array count]); 
    return [array objectAtIndex:index]; 
} 
+0

最好是使用arc4random()。如果未提供種子,則每次運行該應用都會返回sam序列。 – zaph

+0

@CocoaFu首先,這就是爲什麼我將討論鏈接到man手冊,並在代碼示例中提到了可變隨機方法。其次,你有沒有試過每次都用不同的種子來調試一個程序? – Kevin

+0

直到你到了這個部分被徹底調試和工作的地步,是的。當它與一個流一起工作時,您可以去嘗試其他流。無論如何,挑選財富並不需要密碼級別的隨機性。客戶不會記錄一百萬個選擇,並抱怨1/1,000,000的偏見。 – Kevin

1

你可能要使用arc4random()從0-9中選取一個對象。然後,簡單地做

NSString* string = [array objectAtIndex:randomPicked]; 

獲取條目的文本。

+0

完美。我設法使用arc4random()來獲得隨機數,但是在提取文本時遇到了麻煩。謝謝。 –

1

您可以使用arc4random()%10獲得索引。有一點偏差,這不應該是一個問題。

更好的是,使用arc4random_uniform(10),沒有偏見,甚至更容易使用。

+0

嘿,我以爲你有安全背景! 'arc4random_uniform'沒有偏見,應該在這裏使用。 –

+0

對,'arc4random_uniform()'是使用的正確函數。我提到了一個輕微的偏見,對於mod 10,偏見是微乎其微的。我添加了一個糾正附錄。 – zaph