原文地址:http://howtomakeiphoneapps.com/2009/05/how-to-use-random-numbers-in-your-iphone-app/
Would you like your iPhone app to be able randomly pick a number between 1 and 10 or to randomly select one string from a list?
Getting this done requires us to use the random function - a regular old C function. In this post, I am going to show you how to create an array of objects and then use a random number to select one object from the list.
FIrst, use the import statements to import these two libraries: stdlib and time. Put this code into the top of your file:
#import "stdlib.h"
#import "time.h"
Now, create an array and populate it with strings that will serve as our objects:
NSMutableArray *arrayOfObjects = [[NSMutableArray alloc] init];
[arrayOfObjects addObject:@"Object One"];
[arrayOfObjects addObject:@"Object Two"];
[arrayOfObjects addObject:@"Object Three"];
[arrayOfObjects addObject:@"Object Four"];
[arrayOfObjects addObject:@"Object Five"];
Set the seed to the system clock. This will ensure that you get different results every time your run your app.
srandom(time(NULL));
Here is how to get a random number - the number at the end of the statement indicates what the upper limit is. However, the function returns numbers starting with 0 so in practice you will get five results ranging from 0 to 4.
int r = random() % 5;
At this point we have the random number assigned to r and we can use it in any way we like. This is an example of using this number to pick an object our of our array.
NSLog(@"Object = %@", [arrayOfObjects objectAtIndex:r]);
As you can imagine, there are a lot of fun things that you could do with the random function: game logic, random thing of the week and so on.
What would you like to use the random function for in your app?