如果您只想在每次點擊按鈕時顯示一個隨機數,這裏有一些代碼可以提供幫助。
但是,首先,您用於創建位置的行是錯誤的。做到這一點,而不是:
int position = (arc4random() % 5) + 1; // Creates a random number between 1 and 5.
int position = (arc4random() % 5) - 1; // Creates a random number between -1 and 3.
其次,我建議使用一個NSArray
或NSMutableArray
來保存數據。
我假設你有一個當你按下按鈕時被調用的方法。內部的方法,你可以簡單地把這樣的事情:
int size = 5; // You might want to get the size of your array dynamically, with something like [usedNumbers count];
int position = (arc4random() % size) + 1; // Generates a number between 1-5.
NSNumber *randomNumber = [usedNumbers objectAtIndex:position]; // Here is your random number from the array.
所以..如果添加了數組作爲實例變量到類中,頭文件將是這個樣子:
@interface MyViewController : UIViewController
@property (nonatomic, retain) NSMutableArray *usedNumbers;
- (IBAction)buttonWasClicked:(id)sender; // Remember to connect it to your button in Interface Builder.
@end
而你的實現文件:
@implementation MyViewController
@synthesize usedNumbers;
- (void)viewDidLoad {
// Initialize your array and add the numbers.
usedNumbers = [[NSMutableArray alloc] init];
[usedNumbers addObject:[NSNumber numberWithInt:4]];
[usedNumbers addObject:[NSNumber numberWithInt:13]];
// Add as many numbers as you'd like.
}
- (IBAction)buttonWasClicked:(id)sender {
int size = [usedNumbers count];
int position = (arc4random() % size); // Generates a number between 0 and 4, instead of 1-5.
// This is because the indexes in the array starts at 0. So when you have 5 elements, the highest index is 4.
NSNumber *randomNumber = [usedNumbers objectAtIndex:position]; // The number chosen by the random index (position).
NSLog(@"Random position: %d", position);
NSLog(@"Number at that position: %@", randomNumber);
}
@end
如果你這樣做,每次單擊按鈕時都會從數組中選擇一個隨機數。如果您沒有啓用ARC,請記住release
您的所有對象。
PS:這裏還有其他幾個關於這個主題的問題。請記住在提問前進行搜索。
更新:
要確保每個數字只能使用一次,你可以從你的陣列在選擇時,也將其刪除。所以buttonWasClicked:
方法是這樣的:
- (IBAction)buttonWasClicked:(id)sender {
int size = [usedNumbers count];
if (size > 0) {
int position = (arc4random() % size);
NSNumber *randomNumber = [usedNumbers objectAtIndex:position];
// Do something with your number.
// Finally, remove it from the array:
[usedNumbers removeObjectAtIndex:position];
} else {
// The array is empty.
}
}
的[規範的方法,以隨機目標C一個NSArray(
可能重複http://stackoverflow.com/questions/791232/canonical-way-to-randomize -an-nsarray-in-objective-c),[非重複的隨機數字](http://stackoverflow.com/questions/1617630/) – outis
另請參見[什麼是洗牌NSMutableArray的最佳方式?](http:/ /stackoverflow.com/questions/56648/) – outis
[唯一隨機數在整數數組中]的可能重複(http://stackoverflow.com/questions/1608181/)或[非重複隨機數](http:// stackoverflow.com/questions/1617630/) –